繁体   English   中英

将值从Ajax调用传递给PHP

[英]Pass value to from ajax call to PHP

$.ajax({
 url: 'test.php',
 type: "POST",
 data: registerForm.serialize(), region: $("#regio option:selected").text(),
 success: function(data) {
 console.log(data)
 }
});

现在我用它通过registerForm.serialize()获取所有数据,我可以使用$_POST['the_name'];在test.php中调用它们$_POST['the_name'];

现在,每当我在test.php中echo $_POST['region']时,我都需要传递给test.php $("#regio option:selected").text() ,它看不到区域属性,即时消息在ajax内部发送来测试.php。

我如何将$("#regio option:selected").text()传递给test.php并在test.php中调用它。

您可以在其中添加另一个查询字符串:

data: registerForm.serialize() + '&region=' + $("#regio option:selected").text(),

然后,将其视为PHP中的普通发布值

$region = $_POST['region'];

让我们重新缩进代码:

$.ajax({
   url: 'test.php',
   type: "POST",
   data: registerForm.serialize(), 
   region: $("#regio option:selected").text(),
   success: function(data) {
      console.log(data)
   }
});

上面的代码在对象上定义了一个region属性,该属性已传递给$.ajax() region属性不属于data属性,实际上您的data属性甚至都不是对象。 另一个答案表明,您可以使用字符串串联添加另一个查询参数,或者使用serializeArray方法并将对象推入返回的数组中:

// returns an array of objects with `name` and `value` properties 
var postData = registerForm.serializeArray();
postData.push({
   name: 'region',
   value: $("#regio option:selected").text()
});

$.ajax({
   url: 'test.php',
   type: "POST",
   data: postData, 
   success: function(responseData) {
      console.log(responseData);
   }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM