gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:49 25 4
gpt4 key购买 nike

我可以在我的 $.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"/>

现在我有动态生成的变量(检查上面的隐藏片段)。所以要在 $.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"/>

Also would like to know how to prevent from getting SQL Injection

谢谢!

最佳答案

您不能在 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 注入(inject)

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

关于javascript - 在 $.post 中创建动态变量赋值 - JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35156112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com