【问题标题】:Sending data using ajax to php file not working使用ajax向php文件发送数据不起作用
【发布时间】:2020-01-11 18:10:23
【问题描述】:

我正在尝试将字段中的数据发送到 PHP 文件,但它总是返回 null。

我的方法是否正确,或者我遗漏了什么?

提前致谢。 我的ajax


$.ajax({
url: '/GetData.php',
dataType: 'json',
type: 'POST',
data: {
a:a,
b:b,
c:c
},
contentType: 'application/json',
success: function(response){
console.log('success '+ JSON.stringify(response));
search_table =  JSON.stringify(response)

$('#mytable').html(search_table);

},
error: function(err){
console.log('error '+JSON.stringify(err));
//alert(JSON.stringify(err))
}
});


我的 GetData.php 文件

<?php
 $a = $_GET["a"];
 $b = $_GET["b"];
 $c = $_GET["c"];

$remote_url = "http://mydomain/GetDataDetails/?name=".$a."&age=".$b."&degree=".$c;
$opts = array(
'http'=>array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method'=>"GET",
)
);
$context = stream_context_create($opts);
$out=json_decode(file_get_contents($remote_url, false, $context),true);
header('Content-Type: application/json');
echo json_encode($out);
?>

【问题讨论】:

  • 你使用 POST 方法,在 GetData 中使用 GET 方法,像 $a = $_POST["a"]; 一样更改或在 ajax 方法中更改方法
  • 发布代码时,确保其格式合理。您想让我们尽可能轻松地阅读它。
  • 您也可以从 ajax 请求中删除 contentType: 'application/json',因为您很可能只想以“正常”方式发布数据。
  • @SimoneRossaini 感谢您的重播。我试试你说的,但还是不行。
  • 因此,您没有修复代码的格式,而是让它变得更糟。请正确缩进您的代码。没有任何缩进就很难跟上流程。

标签: php ajax


【解决方案1】:

评论回复:

  • 在 PHP 中从 $_GET 更改为 $_POST
  • 从 Ajax 请求中删除 contentType: 'application/json',

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 2014-01-11
    相关资源
    最近更新 更多