简体   繁体   English

为什么PHP无法接收通过AJAX发送的POST数据?

[英]Why does PHP not receive POST data sent via AJAX?

I've seen this many times before on Stack Overflow and other websites, but none of the previous posts seem to be helping. 我之前在Stack Overflow和其他网站上已经看到过很多次,但是以前的帖子似乎都没有帮助。

Assume the following HTML code: 假定以下HTML代码:

<input maxlength="50" size="50" id="searchTxt" />

And assume the following AJAX call: 并假设以下AJAX调用:

$.ajax({
    type: "POST",
    url: "tdat.php",
    data: {userresponse: $('#searchTxt').val()},
    success: function(){
        $('#searchTxt').val("")
    }
})

What should happen is that the data "userresponse" gets posted to the server, having the value of whatever is inside the input box, and then the input in the box is emptied. 应该发生的是,数据“用户响应”被发布到服务器,并具有输入框内任何值,然后清空该框中的输入。

Later, I have the following PHP code in tdat.php: 稍后,我在tdat.php中具有以下PHP代码:

<?php
    if(isset($_POST['userresponse'])){
        $userResponsePHP = $_POST['userresponse'];
        switch($userResponsePHP){
            case "yes":
            echo "alert(\"hi\")";
            break;
        case "no":
            echo "alert(\"negative!\")";
            break;
        default:
            echo "alert(\"nope.\")";
            break;
        }
    }
?>

The PHP does not respond, even if the AJAX call works perfectly. 即使AJAX调用工作正常,PHP也不会响应。 PHP does not even receive the value of "userresponse". PHP甚至没有收到“ userresponse”的值。 I have checked the file paths, localhost connection, adding quotes to "userresponse", and practically all other minor issues stated in other threads, but the problem persists. 我已经检查了文件路径,本地主机连接,在“用户响应”中添加了引号,以及其他线程中所述的几乎所有其他次要问题,但是问题仍然存在。 The AJAX call clears the value of searchTxt, thus it is a successful send. AJAX调用清除searchTxt的值,因此发送成功。 No errors are shown in the console . 控制台中未显示任何错误 Why is this so? 为什么会这样呢?

Try the following: 请尝试以下操作:

$.ajax({
    type: "POST",
    url: "tdat.php",
    data: {userresponse: $('#searchTxt').val()},
    success: function(data){
        alert(data.message);
        $('#searchTxt').val("");
    }
})

php: PHP:

<?php
    header('Content-Type: application/json');
    if(isset($_POST['userresponse'])){
        $userResponsePHP = $_POST['userresponse'];
        switch($userResponsePHP){
            case "yes":
            echo json_encode(["message"=>"hi"]);
            break;
        case "no":
            echo json_encode(["message"=>"negative"]);
            break;
        default:
            echo json_encode(["message"=>"nope"]);

            break;
        }
    }
?>

Note: if the page is refreshing you aren't doing any ajax 注意:如果页面正在刷新,则您没有做任何ajax

The following code snippet works, however it's generally recommended not to use eval I'm using eval in this case because you have the JavaScript alert function on the server-side (in the PHP). 以下代码段有效,但是通常建议不要使用eval,因为在服务器端(在PHP中)具有JavaScript警报功能,因此在这种情况下我将使用eval。 What you should do is echo the text and then call the alert function on the Javascript side. 您应该做的是回显文本,然后在Javascript端调用Alert函数。 However, in the interest of changing as little as possible to your code I'm leaving it as is and only making changes in the JavaScript. 但是,为了尽可能少地更改您的代码,我将其保留原样,仅在JavaScript中进行更改。

2 things to make note of in this example I initialize the text box with one of your accepted values 'yes'. 在此示例中需要注意的两件事:我使用您接受的值“是”初始化文本框。 Of course you can change this so the ajax call is made on say a button click (wasn't sure what your use case was) 当然,您可以更改此设置,以便在单击按钮时进行ajax调用(不确定您的用例是什么)

One small thing you forgot was to read in the data parameter in the success callback. 您忘记的一件事是在成功回调中读取data参数。

<script   src="https://code.jquery.com/jquery-2.2.3.min.js"   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
   $('#searchTxt').val("yes");
       $.ajax({
           type: "POST",
           url: "tdat.php",
           data: {userresponse: $('#searchTxt').val()},
           success: function(data, textStatus, jqXHR) {
              eval(data);
              $('#searchTxt').val("")
           }
        })
    });
</script>
<input maxlength="50" size="50" id="searchTxt" />

Modify your ajax function first as follows: 首先修改ajax函数,如下所示:

$('#searchTxt').change(function(){
    $.ajax({
        type: "POST",
        url: "tdat.php",
        data: {userresponse: $('#searchTxt').val()},
        success: function(res){
            $('#searchTxt').val("");
            console.log(res);
        }
     });
 });

On the change event of searchTxt your ajax call will be executed and then check the console. searchTxt发生更改事件时,将执行ajax调用,然后检查控制台。

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

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