douzhi3667 2014-05-20 09:58
浏览 63
已采纳

从PHP访问POST字符串

I use JQuery.ajax to send a JavaScript object to a PHP script per POST. JQuery sends it in a way that makes it easily accessable from PHP:

JavaScript:

var request = $.ajax({
    url: server,
    dataType: 'text',
    timeout: timeout,
    type: 'POST',
    data: {key:"value"}
});

PHP:

$_POST["key"]

When I send a simple string with $.ajax instead of a JS object, how can I access it in PHP? E.g. when simply sending "data", count($_POST) returns 0.

var request = $.ajax({
    url: server,
    dataType: 'text',
    timeout: timeout,
    type: 'POST',
    contentType: "text/plain",
    data: "data"
});

Do I have to use file_get_contents('php://input') or is there another way?

  • 写回答

2条回答 默认 最新

  • dongpu1331 2014-05-20 10:08
    关注

    When I send a simple string with $.ajax instead of a JS object, how can I access it in PHP?

    Do I have to use file_get_contents('php://input')

    Yes. If you don't encode the data in a format that PHP can decode automatically, then you have to access the raw data like that.

    Remember to set the content-type of the request to text/plain when you do that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?