2016-09-21 123 views
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()没有奏效。我知道有大量的代码,以便保持简单我需要知道以下内容:

  1. 是否在js文件中创建的var数组正确地完成?我需要创建一个JSON对象以下列格式使用AJAX发送的详细信息:

阵列= [{ “PID”= 1时, “扣除”= a_value},{ “PID”= 2,“扣除“= another_value},{”pid“= 3,”deduct“= another_value}]

  1. js文件中的ajax调用是否正确?我使用JSON.stringify()将上述数组转换为json以通过ajax发送。

  2. 我在stock-c.php中正确地循环访问数组吗?我需要将“pid”和“deduct”作为数字变量发送给deductMainstock()方法。

回答

1
  1. 请更改变量名var new以来的保留关键字别的东西。
  2. var updateArray = JSON.stringify(array);你不需要串列化数组。
  3. 将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

后值将数组所以从你的代码中删除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; 

?> 

希望这会有所帮助。