簡體   English   中英

jquery 無法讀取 json 響應(使用 $.post)

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

我正在提交數據類型為 json 的發布請求。 我能夠在 fiddrel 中看到 json 響應,但 jquery 無法解析。

這是我的代碼:

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

這是我在提琴手中的原始響應文本。

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

{"result":"22"}

在 jquery 完成 function 我看到以下值:

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

知道我在這里做錯了什么嗎? 謝謝

您需要使用數據的結果屬性:

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

如果您正在執行cross browser請求,請使用 jquery 的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);
}   

});

根據要求,這是我以答案形式發表的評論:

由於同源政策,您可能會成為限制的受害者。 確保您的請求被發送到您的頁面所在的同一台服務器。 例如,如果您正在請求http://localhost/api/number/substract ,那么您當前的請求頁面必須位於http://localhost

從同一台服務器發出請求解決了我的問題。 感謝 gilly3 的評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM