开发者

jquery unable to read json response (using $.post)

I am submitting a post request with data type json. I am able to see json response in fiddrel but jquery is not able to parse that.

Here is my code:

$("#jsonTestCasePost").click(function(){
        var requestType = $("#requestType").val();
        $('#result').val(requestType);
        debugger;
        $.post("http://localhost/api/number/substract", {numberA:"32",numberB:"10"},
         function(开发者_如何学Godata){
            debugger;
            $('#result').val(data);
         }, requestType);
});

This is my raw response text in fiddler.

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 15
Server: Jetty(6.1.11)

{"result":"22"}

In jquery done function I see following values:

status: 0
statusTex: "", 
responses: {}
headers: ""

Any idea what am I doing wrong here? Thanks


You need to use data's result property:

$('#result').val(data.result);


As requested, here's my comment in the form of an answer:

You are probably falling victim to restrictions due to the same origin policy. Make sure your request is being sent to the same server your page is on. Eg, if you are requesting http://localhost/api/number/substract, your current requesting page must be at http://localhost.


in the case you are doing cross browser request use jquery's ajax

$.ajax({
url:'http://localhost/api/number/substract',
type:'POST',
data:{numberA:"32",numberB:"10"},
dataType:'json',
async:false,
cache:false,
crossDomain:true,
success:function(data){
$('#result').val(data.result);    
},
error:function(jxhr){
console.log(jxhr.responseText);
}   

});


Making request from the same server solved my problem. Thanks gilly3 for you comment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜