2010-11-10 81 views
0

我需要以jQuery.ajax调用的形式重新格式化以下函数以执行错误处理(脚本显然会在某些调用中超时)。如果转换为带有错误回调和成功回调的.ajax(),这会是什么样子?帮助将此jQuery.getJson转换为jQuery.ajax()

jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/tobacco" 
    +"appid=myAppID" 
    +"&lang=en" 
    +"&format=json" 
    +"&count=50" 
    +"&view=keyterms" 
    +"&callback=?", 
    function (data) { 
     // if no error, do something, else gracefully exit 
    }); 
+0

你可以用'.ajaxError'。 http://api.jquery.com/ajaxError/ – 2010-11-10 20:54:22

+0

这将给你一个全局错误处理程序,使用一个错误:func – dstarh 2010-11-10 20:56:52

回答

2
$.ajax({ url: "http://boss.yahooapis.com/ysearch/web/v1/tobacco" 
    +"appid=myAppID" 
    +"&lang=en" 
    +"&format=json" 
    +"&count=50" 
    +"&view=keyterms" 
    +"&callback=?", 
    success: function(data){ 
     //do somethign with the data 
     }, 
    error:function(XMLHttpRequest, textStatus, errorThrown){ 
     //do something on error 
    } 
    }); 
+0

你会在哪里插入错误:function()“ – 2010-11-10 20:57:41

+0

jQuery错误函数不能很好地工作与JQuery 1.4,为了可靠的实现使用try/catch。(以防万一你需要错误处理) – t0mcat 2010-11-10 21:15:04

+0

@ t3ch:我可以在我的问题中使用try/catch与我原来的代码(vs转换成.ajax为FatherStorm建议? – 2010-11-11 17:05:26

0

我知道这是5年过去了,但你可能不应该构建自己的查询字符串

$.ajax({ url: "http://boss.yahooapis.com/ysearch/web/v1/tobacco", 
    data: {appid: "myAppID", 
     lang: "en", 
     format: "json", 
     count: "50", 
     view: "keyterms", 
     callback: "?"}, 
    type: "GET", 
    dataformat: "JSON", 

    success: function(data){ 
     //do something with the data 
    }, 

    error:function(XMLHttpRequest, textStatus, errorThrown){ 
     //do something on error 
    } 
});