我有生成JSON字符串的代码。该代码生成的示例字符串如下所示。我已通过JSON lint工具对其进行了验证,并且验证完美。
{"ShipToName" : "( ) CARPINTERIA CA", "ShipToAddress1" : "3785 SANTA CLAUS LANE", "ShipToAddress2" : "", "ShipToCity" : "CARPINTERIA", "ShipToState" : "CA", "ShipToZip" : "93013", "ShipVia" : "UPS", "Terms" : "01", "SalesRep" : "KV1" }
然后我有一些JQuery将解析该字符串。现在我只是想提醒字符串的一个部分,以确保代码正常工作。我尝试了以下两种方法但没有成功:
尝试#1:提醒'未定义'
function hidShipTo_IndexChanged(sender, args) {
var strComboID = $find("<%=rcbCustomer.ClientID%>");
var strValue = strComboID.get_value();
var strShipToVal = $("#hidShipTo").val();
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
alert("yes");
$.ajax({
type: "POST",
url: "/webservices/ProductServer.asmx/PopulateShipToDetails",
data: strData,
contentType: "application/json; character=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.SalesRep);
},
failure: function (xhr, ajaxoptions, thrownError) {
alert("Error1:" + xhr.status);
alert("Error2:" + thrownError);
}
});
}
尝试#2:在JQuery库对象中抛出错误
function hidShipTo_IndexChanged(sender, args) {
var strComboID = $find("<%=rcbCustomer.ClientID%>");
var strValue = strComboID.get_value();
var strShipToVal = $("#hidShipTo").val();
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
alert("yes");
$.ajax({
type: "POST",
url: "/webservices/ProductServer.asmx/PopulateShipToDetails",
data: strData,
contentType: "application/json; character=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.SalesRep);
},
failure: function (xhr, ajaxoptions, thrownError) {
alert("Error1:" + xhr.status);
alert("Error2:" + thrownError);
}
});
}
关于如何访问JSON字符串中的每个项目的任何想法?
谢谢!
答案 0 :(得分:1)
因为你的代码没有抛出一个未定义的异常,所以我们可以推断'msg'并不是未定义的。
使用调试器查看你的msg真正包含的内容:
alert(msg.SalesRep);
console.log(msg);
注意:contentType应为'charset = utf-8',而不是'character = utf-8'。你发送的字符串也是无效的json。它应该是双引号而不是单引号。
答案 1 :(得分:1)
所以,一旦我检查了控制台日志,答案就非常简单了。我添加了这行代码,我能够开始访问JSON字符串中的所有内容:
var obj = $.parseJSON(msg.d);
答案 2 :(得分:0)
这没有任何意义:
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
应该只是
var strData = { strSoldToSelected: strValue, strShipToSelected: strShipToVal };