簡體   English   中英

Ajax POST方法在PHP中不起作用,但是GET在起作用

[英]Ajax POST method not working in PHP, but GET is working

我正在嘗試使用Ajax向php發送POST請求。

如果我使用GET可以正常工作,但是使用POST時,我在php中收到的數據為空。 我正在將數據作為json發送。

js代碼如下所示:

$.ajax(
        {
            type: 'POST',
            url: 'php/GiveItBack.php',
            contentType: "json",
            data: {
                word: 'abc'
            },
            success: function (json) {
                alert(json);
            },
            error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
        });

這是php / GiveItBack.php文件

<?php

$x = $_GET['word'];
echo 'Get: ' . $x;

$x = $_POST['word'];
echo '; Post: ' . $x;

$x = $_REQUEST['word'];
echo '; Request: ' . $x . ';';

?>

使用此代碼,警報窗口中的消息如下所示:

獲取: 帖子:; 要求:

如果我將js文件中的類型:“ POST”替換為類型:“ GET”,這是我在警報窗口中得到的結果(正如我期望的那樣):

得到:abc; 帖子:; 要求:abc;

我看不到我在這里想念的東西。 代碼中有什么問題嗎,或者我需要為此進行任何特殊設置。

順便說一下,我正在使用: jquery-2.2.4.min和php v5.6和XAMPP v3.2.2。

謝謝。

內容類型不正確,需要使用contentType: "application/x-www-form-urlencoded"'Content-Type': 'application/json'

   $.ajax(
    {
        type: 'POST',
        url: 'php/GiveItBack.php',
        contentType: "application/x-www-form-urlencoded",
        data: {
            word: 'abc'
        },
        success: function (json) {
            alert(json);
        },
        error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
    });

contentType: "json",

您的內容類型在這里是錯誤的。 如果您想以嘗試的方式接收它,則應該使用application/x-www-form-urlencoded

如果您仍然想使用JSON,則必須對JSON輸入進行json_decode

$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE);
$.ajax(
    {
        method: 'POST',
        url: 'php/GiveItBack.php',
        data: {
            word: 'abc'
        },
        success: function (json) {
            alert(json);
        },
        error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
    });

刪除contentType: json ,您應該可以使用$_POST superblogal數組。 如果使用contentType: json則包含參數的對象將轉換為字符串,然后發送到服務器。 要獲取字符串,您將需要使用

file_get_contents('php://input');

發生這種情況是因為$_POST僅包含與以下標頭一起發送的數據:

  • 應用程序/ x-WWW窗體-urlencoded
  • 多部分/格式的數據編碼

當您設置contentType: json ,jQuery向$_POST不支持的請求中添加了application/json頭,因此JSON字符串被視為原始輸入,因此您需要使用php://input流來檢索它

Ajax數據刪除contentType: json

$.ajax(
        {
            type: 'POST',
            url: 'php/GiveItBack.php',

        data: {
            word: 'abc'
        },
        success: function (json) {
            alert(json);
        },
        error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM