如何通过AJAX调用Web服务返回Json数据?

时间:2017-06-28 07:27:40

标签: javascript jquery json ajax

我有一个Web服务,它返回JSON数据,而不是用于调用Web服务的代码。



jQuery.ajax({
  url: 'http://localhost:5606/xyz',
  type: "POST",
  contentType: "application/json; charset=utf-8",
  dataType: 'json',
  data: '{"a":"b"}',
  success: function(responses, textStatus, XMLHttpRequest) {
    alert(responses);
  },
  error: function(xhr, err) {
    console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
    console.log("responseText: " + xhr.responseText);
  },
  complete: function() {}
});
};




它将成功函数中的alert输出作为[object object]返回,但我希望它以正确的json格式。

1 个答案:

答案 0 :(得分:1)

您必须阅读JSON.stringify()

使用alert(JSON.stringify(data))

示例:

var response = {};

response.status ="success";
response.data="Your data";

alert(response); //It will give you [object object]
console.log(response); //Gives JSON data in console
alert(JSON.stringify(response)); //Alerts json string

if(response.status == "success")
  //Pass response.data to the next webservice it will still be in the json format.