如何使用AJAX处理从PHP脚本返回的数组
How to work with array returned from PHP script using AJAX?
在过去的几个小时里,我一直在处理这个问题,我希望我能在这里得到解决方案。我想做的是这样的事情:
PHP:
$errorIds = array();
if(error hapens){
array_push($errorIds, $user['userId']);
}
$data['results'] = "success";
$data['message'] = "Your message have been sent successfully";
$data['error_id_array'] = $errorIds;
echo json_encode($data);
和JS:
$.ajax({
type: "POST",
url: HTTPS + '/lib/model/data/ctlSms.php?send=1',
data: $("#smsSendForm").serialize(),
dataType: 'json',
success: function(data){
$("textarea").removeClass("valid");
if(data['results']=="success"){
$('#smsSendForm')[0].reset();
$('.jtable').find("tbody tr").each(function(){
var firstCol = parseInt($(this).find("td:first").text());
var inArray = $.inArray(firstCol, data['error_id_array']);
if(inArray == -1){
$(this).css("background", "green");
} else {
$(this).css("background", "red");
}
});
} else {
console.log(data['message']);
$('.jtable').find("tbody tr").each(function(){
var firstCol = parseInt($(this).find("td:first").text());
var inArray = $.inArray(firstCol, data['error_id_array']);
if(firstCol == data['error_id']){
$(this).css("background", "red");
return false;
} else {
if(inArray == -1){
$(this).css("background", "green");
} else {
$(this).css("background", "red");
}
}
});
}
}
});
我想做的是,如果该数组中有错误,jQuery会检查用户ID数组中是否有一个与jTables ID匹配的ID,以及是否匹配,而不是颜色背景为红色,否则颜色背景为绿色。问题出在这里:
$('.jtable').find("tbody tr").each(function(){
var firstCol = parseInt($(this).find("td:first").text());
var inArray = $.inArray(firstCol, data['error_id_array']); /// here
if(inArray == -1){
$(this).css("background", "green");
} else {
$(this).css("background", "red");
}
});
即使我故意制造了一个错误,我也不会得到可能的匹配。所有东西都是绿色的,后端代码工作得很好,但这个前端让我在过去的几个小时里很沮丧。也许我做错了什么???
编辑:
这就是console.log(data['error_id_array'])返回给我的内容:
["2"]
第2版:
好的,我会从另一个角度问。我如何访问这样形式的JSON对象-console.log-out from data:
Object {results: "success", message: "Your message have been sent successfully", error_id_array: Array[1]}
error_id_array: Array[1]
0: "2"
length: 1
__proto__: Array[0]
message: "Your message have been sent successfully"
results: "success"
__proto__: Object
我需要检查error_id_array 下的数组
尝试使用javascript indexOf而不是inArray,
console.log(data['error_id_array'].indexOf(firstCol)); // Check whether firstCol has the value
相关文章:
- 使用 jQuery 从运行 MySQL 的 PHP 脚本返回信息
- 为什么&此脚本返回的位置未定义
- 使用jquery ajax访问php脚本返回的JSON
- JS脚本返回NaN
- Java脚本返回错误值
- 从Java脚本返回多个值,这些值不能在firefox上运行(在IE上运行良好)
- 如何使用AJAX处理从PHP脚本返回的数组
- JSON对象在控制台中显示对象,但也包含来自php脚本返回的字符串的“未定义”
- 脚本返回页面上不存在的元素
- Google 应用脚本:返回 2 个两个范围之间唯一值的函数
- Photoshop脚本返回输入值
- 如何将控制从php脚本返回到我的主页
- 如何让这个脚本返回数字0-9而不是1-10
- 自定义JavaScript NodeList选择器脚本返回空/未定义
- 如何访问php脚本返回的j-query中的数组
- 如何从php脚本返回检查值到调用页面
- 通过jquery检查PHP脚本返回的数据
- PHP脚本返回整个网页,而不是数据库数据
- 如何让脚本返回一个值
- Swfupload:如何解析从upload.php脚本返回的数据