简体   繁体   English

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

[英]Getting JSON data from jQuery AJAX call on a PHP page

I would like to send data using the jQuery Ajax API: 我想使用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);}
});

When I tried to retrieve this data with PHP using 当我尝试使用PHP检索此数据时

    $param1 = $_REQUEST['param1'];

$param1 is showing null and print_r($_REQUEST) is only showing action = SomeAction .. $param1显示为nullprint_r($_REQUEST)仅显示action = SomeAction ..

How do I retrieve the posted data on a PHP page? 如何在PHP页面上检索发布的数据?

since you're sending the ajax as "contentType: 'application/json'", you need to fetch the request body with php://input like so: 由于您将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);

Try this: 尝试这个:

$params = json_decode( $_POST['param1']);

And then check what you have got: 然后检查您得到了什么:

var_export( $params);

Or you can use a foreach loop: 或者,您可以使用foreach循环:

foreach( $params as $param)
{
    echo $param . '<br />';
}

You are using POST, method, dont use REQUEST because it is also less secure. 您正在使用POST方法,请不要使用REQUEST,因为它也不太安全。

尝试使用

$param1 = $_POST['param1'];

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

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