JavaScript/JQuery:对象属性问题
我正在使用 JQuery 调用 $.ajax 函数。被调用的 php 返回一个结构为“varname=varvalue&varname2=varvalue2”的字符串。我将其全部分解并创建一个对象,该对象使用 varnames 作为属性,使用 varvalues 作为这些属性的值。这是我的代码:
$.ajax({
type:"POST",
url:"/actions/savebbuilderdata.php",
data:({step: stepNum, submitObj: saveObj}),
complete:function(jqXHR, textStatus){
var returnObj = new Object();
var returnArr = jqXHR.responseText.split("&");
for(i=0;i<returnArr.length;i++){
var tempArr = returnArr[i].split("=");
returnObj[tempArr[0]] = tempArr[1];
}
//For Testing that the values are infact being assigned
for(prop in returnObj){
alert(prop + ": " + returnObj[prop]);
}
alert(returnObj.returnText);
}
});
注意第二个 for 循环。我这样做只是为了获得对象内每个属性的警报。这可以正常工作并显示每个属性名称和正确的值。返回的属性之一始终是“returnText”。但是,当我调用最终警报试图获取 returnText 时,我得到“未定义”。有什么想法可能是为什么吗?
I'm calling the $.ajax function using JQuery. The php that is called returns a string structured as such "varname=varvalue&varname2=varvalue2". I'm breaking it all up and creating an object that uses the varnames as properites and the varvalues as values of those properties. Here's my code:
$.ajax({
type:"POST",
url:"/actions/savebbuilderdata.php",
data:({step: stepNum, submitObj: saveObj}),
complete:function(jqXHR, textStatus){
var returnObj = new Object();
var returnArr = jqXHR.responseText.split("&");
for(i=0;i<returnArr.length;i++){
var tempArr = returnArr[i].split("=");
returnObj[tempArr[0]] = tempArr[1];
}
//For Testing that the values are infact being assigned
for(prop in returnObj){
alert(prop + ": " + returnObj[prop]);
}
alert(returnObj.returnText);
}
});
Notice the second for loop. I'm simply doing that to get an alert for each property within the object. This works correctly and shows each property name with the correct value. One of the properties being returned is always 'returnText'. However, when I call the final alert attempting to get that returnText I get 'undefined'. Any ideas why this might be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不将数据作为 json 编码数组返回呢?更容易合作
Why don't you return the data as a json encoded array instead? Much easier to work with
我看不出代码有什么问题,但也许这些可以帮助您识别问题。我会使用
success
而不是complete
来确保问题不在于信息传输。我还将
deparameterize
代码提取到一个单独的函数中,因为它更容易测试,而且看起来像是我会再次执行的操作。注意:扩展 String 并不总是最佳实践,但也许在这种情况下它有效。
I can't see much wrong with the code, but maybe these can help you identify the problem. I would use
success
instead ofcomplete
to make sure the problem isn't in the transfer of information.I also extract the
deparameterize
code into a separate function because it is both easier to test and seems like something I would do again.Note: not always best practice to extend String, but maybe in this case it works.