gpt4 book ai didi

javascript - 解析 JSON 字符串以在 AJAX 成功调用中使用

转载 作者:行者123 更新时间:2023-11-30 17:36:44 25 4
gpt4 key购买 nike

我有生成 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 字符串中的每一项的任何想法?

谢谢!

最佳答案

由于您的代码没有抛出未定义的异常,因此我们可以推断“msg”不是未定义的。

使用调试器查看您的消息真正包含的内容:

alert(msg.SalesRep);
console.log(msg);

注意:contentType 应该是“charset=utf-8”,而不是“character=utf-8”。您发送的字符串也不是有效的 json。它应该是双引号,而不是使用单引号。

关于javascript - 解析 JSON 字符串以在 AJAX 成功调用中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21891199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com