我正在编写一个网页,它从 html 表中读取数据,以便使用 PHP 进行 MySQL 查询。这是 this question 的延续。我让 AJAX 将我需要使用的数据发送到 PHP 文件,并使用代码更新它发送的信息。但是,出现了两个错误。
我收到一条消息,提示
错误:错误:jQuery21405680291895882033_1487801210725 未调用
我发送的数据末尾有一个“:1”,给我一个错误。
如何解决这两个错误?非常感谢!
JS代码:
function getTableData(){
var array = [];
var headers = [];
$('#tablaListado th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#tablaListado tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
if($(this).find("textarea").length){
var costo = $(this).find('textarea').val();
arrayItem[headers[index]] = costo;
}else{
arrayItem[headers[index]] = $(item).html();
}
});
array.push(arrayItem);
});
actualizarCostos(array);
}
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: false,
jsonpCallback: jsonCallback,
cache: true,
data:{ "table_data": JSON.stringify(array[i])},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
},
traditional: true
});
}
}else{
alert("Input must be array");
}
}
function jsonCallback(data, status){
console.log(data + " " + status);
}
PHP 部分:
//Added on top of the page
header('Access-Control-Allow-Origin: *');
...
function updateCosts($json){
conectar();
$array = json_decode($json, true);
echo "<script>console.log('$array');</script>";
$costo = $array["Costo"];
$sku = $array["SKU"];
$instruccion = "UPDATE articulos SET art_cost='$costo' WHERE art_SKU = '$sku'";
return ejecutarInstruccion($instruccion);
}
if(isset($_GET['table_data'])){
foreach($_GET['table_data'] as $index => $item)
{
// do something here
echo "<script>console.log('$item');</script>";
updateCosts($item);
}
// Response back - if needed
echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}
编辑:
我忘了提及,我曾尝试在此代码上将“jsonp”更改为“json”,但收到一条错误消息,指出 PHP 文件不允许外部数据,即使我尝试使用 header('Access -Control-Allow-Origin: *')
在所述文件上。
最佳答案
您的页面返回 JSON,而不是 JSONP。它们不可互换。从 $.ajax()
调用中删除 jsonp
和 jsonpCallback
属性,并将 dataType
更改为 json
:
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: true,
data: {
table_data: JSON.stringify(array[i])
},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status" + status + " \nError:" + err);
},
traditional: true
});
关于javascript - AJAX 做了我需要它做的事情,但仍然出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420563/