帮助处理json响应

时间:2011-05-27 18:12:01

标签: jquery ajax json jsonp

我仍然想弄清楚如何使用json ..有人可以帮助我了解如何处理这个回应。我的疑问是:

$.ajax({
url: s7query,
dataType: 'jsonp',
success: function(){
// how do I deal with the response?
} 
});

我正在查询的json返回(使用1或0):

s7jsonResponse(
{"catalogRecord.exists":"1"},"");

我需要的是数字并将其放入变量中,以便我可以针对该结果运行条件逻辑。感谢您对此有任何帮助......

如果我尝试使用任何函数处理成功,firebug只返回s7jsonResponse未定义。我试图将它定义为请求之外的变量。现在我在firebug中看到它从所有请求中返回json,但是它将它们作为错误返回,现在说s7jsonResponse不是函数。我想我很亲密......请帮忙!

2 个答案:

答案 0 :(得分:1)

好的,我错过了json p部分!您只需要为s7jsonResponse定义一个方法。

function s7jsonResponse (jsonData, someString) {
    alert(jsonData["catalogRecord.exists"]);
    // deal with the response here
}

See this for details on JSONP

初步回复

我注意到catalogRecord.exists,其中有一个.,它不会被提取。如果您没有充分的理由这样做,可以将其更改为catalogRecordExists并使用以下解决方案。

$.ajax({ 
url: s7query, 
dataType: 'json', //removed jsonp in the last edit
success: function(data){ // this is the method that executes on success
            // parseJSON is not required as you already put it in dataType
            // alert(($.parseJSON(data))["catalogRecord.exists"]); 
            alert(data["catalogRecord.exists"]);
         }
});

注意: 您发回的数据应为{"catalogRecord.exists":"1"}

您可以使用$.getJSON执行相同操作(内部调用$.ajax

答案 1 :(得分:1)

您在ajax调用中将jsonp指定为dataType。这告诉Web服务返回jsonp响应,而不是纯json响应。所以,鉴于你得到的响应,你应该定义一个名为s7jsonResponse的函数,它接受两个参数。第一个应该是一个json对象,你必须查看api才能获得第二个,因为在你给我们的例子中它是空的。

在s7jsonResponse方法中,您可以查看返回的数据,但正如Lobo指出的那样,您在名称中有一个点。因此,您必须使用括号表示法访问该属性。类似的东西:

function s7jsonResponse( obj, nothing )
{
    var exists = obj["catalogRecord.exists"];
    // do your stuff with your 1 or 0 which is stored in exists
}