使用Jquery/Javascript访问嵌入在XML中的JSON
我有一个jquery函数,它与ASP.NET web服务进行通信,如下所示使用Jquery/Javascript访问嵌入在XML中的JSON,javascript,jquery,xml,ajax,json,Javascript,Jquery,Xml,Ajax,Json,我有一个jquery函数,它与ASP.NET web服务进行通信,如下所示 $(document).ready(function() { $.support.cors = true; $.ajax({ type: "GET", url: "http://www.webservice.com/blahblah.asmx/blahb123",
$(document).ready(function() {
$.support.cors = true;
$.ajax({
type: "GET",
url: "http://www.webservice.com/blahblah.asmx/blahb123",
data: "tnWsGuid=TEST1",
dataType: "text",
success: function(data, status, jqxhr) {
xmlString = data;
alert(xmlString);
},
error: function (request, status, error) {
alert(status);
}
});
});
警报显示如下所示:
<?xml version="1.0" encoding = "utf-8"?>
<string xmlns = "http://Walkthrough/XmlWebServices/">
{"approverName":"","emailAddress":"","companyName":"ABC","address":{"streetAddress1":"12 BlahBlah","streetAddress2":"","state":"ON","zipCode":"","country":"SO","phoneNumber":""},"tabledata:"[{"vendorPart":"AAAAA","partDescription":"N/A","price":"0.00","quantity":"28"},{"vendorPart":"BBBBBBB","partDescription":"N/A","price":"0.00","quantity":"3"},{"vendorPart":"CCCCCC","partDescription":"N/A","price":"0.00","quantity":"25"}]}
</string>
但是返回了一个无效字符的错误,该错误出现在IE调试器中
知道如何访问xml信封中的数据并将其转换为JSON对象以便将其解析为JSON吗?我无法更改web服务,因此必须在网页中完成所有操作。我认为您的子字符串正在向JSON数据添加结束标记。 那么:
xmlString = $.parseXML(xmlString);
var jsondata = $.parseJSON($(xmlString).children('string').text());
您可以这样做:
success: function(data, status, jqxhr) {
var xml = $($.parseXML(data)), // Parse the XML String to a Document, and Wrap jQuery
json = xml.find("string").text(), // Get the text of the XML
jsonObj = $.parseJSON(json); // Parse the JSON String
}
或短符号
var jsonObj = $.parseJSON($($.parseXML(data)).find("string").text());
Live Fiddle:当您的呼叫返回xml时,您可以使用
数据类型:“xml”
而不是“文本”
然后,您可以处理xml响应:
var jsonData=$.parseJSON(data.find("string").text());
请注意,
$.support.cors=true
实际上不会做任何事情,除非当前浏览器支持cors,而jQuery错误地检测到它不支持cors。有什么原因让您在XML中使用JSON而不是直接返回JSON吗?这对我来说很有效,对它进行了测试,并在警报中使用了jsonObj.companyName,它显示了正确的内容!将此标记为答案,谢谢!您忘记了数据必须是$(数据)。除此之外,我更喜欢这个答案。
var jsonData=$.parseJSON(data.find("string").text());