在 $.post - JQuery 中创建动态变量赋值


Create dynamic variable assignment inside $.post - JQuery

我可以在$.post JQuery/Ajax代码中使用动态变量吗?我想知道我在哪里犯了错误,或者我误解了 JQuery $.post的使用。

我已经动态地创建了变量和从text-fields分配给它的值。现在我想在 JQuery $.post中使用这些变量。

代码如下:

工作正常的部分:

var boxFields = ["customerId","customerName","customerContact","customerEmail"];
var boxVar = [];
for(var x=0;x<4;x++)
{
	boxVar[x] = $("#" + boxFields[x]).val();
}
alert(boxVar[1]); //Just random call to check it works.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="customerId" value="12345"/>
<br>
<br>
<input type="text" id="customerName" value="John Doe"/>
<br>
<br>
<input type="text" id="customerContact" value="XXXXXXXXXX"/>
<br>
<br>
<input type="text" id="customerEmail" value="xxxxxx@xxx.com"/>

现在我动态生成变量(check above hidden snippet for that).所以在$.post中使用那些.

更新:

抱歉,错过了实际部分

我的问题/问题:我可以使用 for 循环在 $.post 中创建动态对象吗?

整个代码:

var boxFields = ["customerId","customerName","customerContact","customerEmail"];
var boxVar = [];
for(var x=0;x<4;x++)
{
	boxVar[x] = $("#" + boxFields[x]).val();
}
$.post("url.php",
{
  requestType: "updateRow",
  
  for(var y=0;y<4;y++)
  {
    boxFields[y]: boxVar[y] 
    if(y!=3){,}  
  }
  
  /* I want above code to work like this:
  requestType: "updateRow",
  customerId: 12345,
  customerName: John Doe,
  customerContact: XXXXXXXXXX,
  customerEmail: xxxxxx@xxx.com
  */
},
function(data)
{
 //Success Code Lines..........
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="customerId" value="12345"/>
<br>
<br>
<input type="text" id="customerName" value="John Doe"/>
<br>
<br>
<input type="text" id="customerContact" value="XXXXXXXXXX"/>
<br>
<br>
<input type="text" id="customerEmail" value="xxxxxx@xxx.com"/>

还想知道如何防止获得SQL注入

谢谢!

你不能在 post 函数中放置循环(循环不是对象),但你可以在 post 之前构造数据。更清洁的方法是:

var data = {
  requestType: "updateRow"
};
$('input').each(function() { // change the selector to be more precise
  data[$(this).attr('id')] = $(this).val();
});
console.log(data);
$.post("url.php", data, function(data) {
  //Success Code Lines..........
});

SQL注入

即使你可以在JS中进行一些检查,真正防止SQL注入的唯一方法是在服务器端与SQL数据库交互时转义/检查/使用特殊方法。

我可以使用 for 循环在 $.post 中创建动态对象吗?

不在呼唤.post()没有。 这与.post()本身或AJAX或类似的东西无关,而只是作为语言的语法。 考虑您的尝试:

$.post("url.php",
{
  requestType: "updateRow", 
  for(var y=0;y<4;y++)
  {
    boxFields[y]: boxVar[y] 
    if(y!=3){,}  
  }
  //...

函数的第二个参数只是一个对象。 循环和其他控制结构之类的东西对于声明对象无效。 你能做的是,嗯,你以前已经做过的事情。 构建对象,然后在函数调用中使用它:

var someArray = [];
for(var x = 0; x < 4; x++)
{
    someArray[x] = someValue;
}
// etc.
// later...
$.post('url.php', someArray, function () { /.../ });

基本上,循环不是可以传递给函数的对象。 它是命令式代码的控制结构。