php - 从 PHP 页面上的 jQuery AJAX 调用获取 JSON 数据

标签 php jquery ajax json

我想使用 jQuery Ajax API 发送数据:

var myData = {"param1" : $('#txtParam1').val(), "param2" : $('#txtParam2').val()};

$.ajax({
    url: 'DataService.php?action=SomeAction',
    type: 'POST',
    data: myData,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(result) {
    alert(result.Result);}
});

当我尝试使用 PHP 检索此数据时

    $param1 = $_REQUEST['param1'];

$param1 显示 nullprint_r($_REQUEST) 仅显示 action = SomeAction ..

如何检索 PHP 页面上发布的数据?

最佳答案

由于您将 ajax 作为“contentType: 'application/json'”发送,因此您需要使用 php://input 获取请求正文像这样:

$request = file_get_contents("php://input"); // gets the raw data
$params = json_decode($request,true); // true for return as array
print_r($params);

关于php - 从 PHP 页面上的 jQuery AJAX 调用获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1984552/

相关文章:

java - 在PHP中获取Java编译错误

php - 在 ubuntu 18.04 中设置 php 时区

javascript - 尽管我使用 # idname 选择了所有 ID,但为什么所有 ID 都没有更改?

javascript - 将属性无效的 html5 替换为 jquery

javascript - 将未定义常量与 Angular 一起使用

php - mysql_fetch_assoc() 期望参数 1 是资源,在第 9 行的 C :\xampp\htdocs\qcc\truckdelivery. php 中给出的 bool 值没有选择数据库

php - 在 Prestashop 的注册表中添加地址字段

jquery - 在 JQuery 中处理 F5

jquery - 正在加载等待AJAX​​请求的图像

javascript - 如何将 JavaScript 字符串下载为文件