0
我想在js中创建json对象,使用ajax将其发送到php页面并通过它在php页面中循环。通过创建和循环json对象的问题
我的代码如下
表单页面
<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");
}
});
}
});
股票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;
股票类的股票存在-m.php,我可以配置该方法deductMainstock()的作品(包括一个mysqli更新查询)。
但是,当运行我的代码似乎deductMainStock()没有奏效。我知道有大量的代码,以便保持简单我需要知道以下内容:
- 是否在js文件中创建的var数组正确地完成?我需要创建一个JSON对象以下列格式使用AJAX发送的详细信息:
阵列= [{ “PID”= 1时, “扣除”= a_value},{ “PID”= 2,“扣除“= another_value},{”pid“= 3,”deduct“= another_value}]
js文件中的ajax调用是否正确?我使用JSON.stringify()将上述数组转换为json以通过ajax发送。
我在stock-c.php中正确地循环访问数组吗?我需要将“pid”和“deduct”作为数字变量发送给deductMainstock()方法。