我试图在js中创建一个json对象,使用ajax将其发送到php页面并在php页面中循环。
我的代码如下
表单页面
<html>
<body>
Input 1: <input type="text" data-id="1" data-old="30"/><br>
Input 2:<input type="text" data-id="2" data-old="40"/><br>
Input 3:<input type="text" data-id="3" data-old="50"/><br>
<input type="text" id="max" value="3" hidden/>
<button type="button" id="proceed">Go</button>
</body>
</html>
js
$("#proceed").on("click",function(){
var num=$("#max").val();
var array=[]; //[] or {} ??
for(i=1;i<=num;i++){
var old=$('input[data-id="'+i+'"]').data("old");
var new=$('input[data-id="'+i+'"]').val();
var deduct;
if(new!==old && new!==""){
deduct=old-new;
array.push({"pid":i,"deduct":deduct});
}
var updateArray = JSON.stringify(array);
$.ajax({
type:"POST",
url:"../control/stock-c.php",
data:{updateArray:updateArray, func:"manualSync"},
dataType:"json",
success:function(){
alert("yay");
}
});
}
});
stock-c.php
require_once '../model/stock-m.php';
$updateArray=$_POST["updateArray"];
$array= json_decode($updateArray);
$obj=new Stock();
foreach($array as $obj1){
$result=$obj->deductMainstock($obj1->pid,$obj1->deduct);
}
return $result;
Stock类存在于Stock . m.php中,并且我可以确认方法deductMainstock()有效(包括mysqli更新查询)。
然而,当运行我的代码时,似乎演绎mainstock()没有工作。我知道有大量的代码,所以为了保持简单,我需要知道以下内容:
- 在js文件中创建的var数组是否正确??我需要创建一个json对象,以以下格式使用ajax发送详细信息:
阵列=[{"pid"= 1,"扣除"= a_value},{"pid"= 2,"扣除"= another_value},{"pid"= 3,"扣除"= another_value}]
js文件中的ajax调用是否正确?我使用json .stringify()将上面的数组转换为json,以便通过ajax发送。
我是否在stock . c.php中正确地循环数组?我需要发送"pid"answers"扣除"作为数字变量到扣除mainstock()方法。
- 请将变量名称
var new
更改为其他名称,因为它是保留关键字。 -
var updateArray = JSON.stringify(array);
不需要对数组进行字符串化。 - 将ajax调用移出
for
循环。
<script>
$("#proceed").on("click",function(){
var num=$("#max").val();
var array=[]; //[] or {} ??
for(i=1;i<=num;i++){
var old=$('input[data-id="'+i+'"]').data("old");
var new_val=$('input[data-id="'+i+'"]').val();
var deduct;
if(new_val!==old && new_val!==""){
deduct=old-new_val;
array.push({"pid":i,"deduct":deduct});
}
}
if(array.length){
$.ajax({
type:"POST",
url:"../control/stock-c.php",
data:{updateArray:array, func:"manualSync"},
dataType:"json",
success:function(){
alert("yay");
}
});
}
});
</script>
PHP Post值将是数组,因此从代码中删除json_decode
。
<?php
require_once '../model/stock-m.php';
$array = $_POST["updateArray"];
$obj = new Stock();
foreach ($array as $obj1) {
$result = $obj->deductMainstock($obj1->pid,$obj1->deduct);
}
return $result;
?>
希望这将帮助。