将值从 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()获取所有数据,我可以在测试中调用它们.php $_POST['the_name'];

现在我需要通过测试.php $("#regio option:selected").text()每当我在测试中echo $_POST['region']时.php它都看不到 im 在 ajax 内部发送以进行测试的区域属性.php。

如何通过$("#regio option:selected").text()进行测试.php并在测试中调用它.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)
   }
});

上面的代码在已传递给 $.ajax() 的对象上定义了一个 region 属性。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);
   }
});