【问题标题】:cannot get value from php ajax无法从 php ajax 获取价值
【发布时间】:2018-06-25 03:33:04
【问题描述】:

无法从 php true AJAX 获取值。

我的php代码是

<?php
$name =  $_POST['name'];
$hobby = $_POST['hobby'];
if (!empty($name and $hobby)){
echo 'Data was succesfully captured';
}else {
echo 'Data was not captured'
}

我的html代码是

<div id="result"></div>

<form method="post">
<input name="name" type="text" id="name">
<br>
<input name="hobby" type="text" id="hobby">
<input name="snd_btn" type="button" id="snd_btn" value="Save">
</form>

JS

$(document).ready(function(){
$('#snd_btn').click(function() {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
 url: "save.php",
 type: "POST",
dataType: 'json',
data: { name, hobby,
success: function(result) {
$('#result').html(result);
  },
}
 });
 });
   });

如果我把js改成

success: function() {
$('#result').html('Data was succesfully captured');
},

它可以工作,但不是来自 php

【问题讨论】:

  • 真正的 AJAX 是什么意思?
  • 用ajax从php接收数据
  • 我已经回答了。希望这有效....
  • save.php 在做什么? save.php 会返回什么输出?
  • 在echo 'Data was not captured' 的行尾加一个分号。有什么变化吗?

标签: php json ajax html


【解决方案1】:

这个是错的。

if (!empty($name and $hobby)) {

请将其替换为:

if (!empty($name) and !empty($hobby)) {

您必须检查每个变量是否为空。

【讨论】:

  • 没关系,但是我没有看到从 php 到 result DIV 的成功消息
【解决方案2】:

问题:

  • hobby 之后是一个“}”,然后是“,”。
  • 然后,您有一个容易出错的附加“}”。 success 回调结束后的“}”(顺便说一句,删除“,”)。
  • 您忘记了 echo 'Data was not capture' 行末尾的分号。
  • ajax 调用需要一个 JSON 编码响应,正如您定义的 dataType: JSON。因此,在 PHP 中,您必须使用 json_encode 对响应字符串进行编码。
  • 由于您没有错误回调 (error: function(...){...}),因此您看不到任何错误。所以,定义一个。下面是一个示例。

建议:

  • 如下定义data对象。
  • PHP 检查空值应该如下所示。
  • 您还必须检查是否设置了发布的值。
  • 不要向用户显示任何特定的错误详细信息。只需向他们显示一般用户友好的消息。所以,不要像我一样 - 在控制台中打印错误详细信息 :-)

index.php:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title></title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#snd_btn').click(function () {
                    var name = $('#name').val();
                    var hobby = $('#hobby').val();

                    $.ajax({
                        method: 'POST',
                        dataType: 'json',
                        url: 'save.php',
                        data: {
                            'name': name,
                            'hobby': hobby
                        },
                        success: function (result, textStatus, jqXHR) {
                            $('#result').html(result);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert('Error! See the console');

                            console.log(textStatus);
                            console.log(errorThrown);
                            console.log(jqXHR);
                        },
                        complete: function (jqXHR, textStatus) {
                            //...
                        }
                    });
                });
            });
        </script>
    </head>
    <body>

        <div id="result"></div>

        <form method="post">
            <input name="name" type="text" id="name">
            <br>
            <input name="hobby" type="text" id="hobby">
            <input name="snd_btn" type="button" id="snd_btn" value="Save">
        </form>

    </body>
</html>

保存.php:

<?php

/*
 * Check if the values are set.
 * I used here the short "null coalescing operator".
 * Search for it in the link below.
 *
 * @link https://secure.php.net/manual/en/language.operators.comparison.php Comparison Operators.
 */
$name = $_POST['name'] ?? '';
$hobby = $_POST['hobby'] ?? '';

if (!empty($name) && !empty($hobby)) {
    $response = 'Data was succesfully captured';
} else {
    $response = 'Data was not captured';
}

echo json_encode($response);

【讨论】:

    【解决方案3】:

    首先你要检查ajax调用是否成功

    如果ajax调用成功,则

    通过打印控制台检查成功数据的响应。

    你的php代码应该是这样的

    <?php
    $name = $_POST['name']; 
    $hobby = $_POST['hobby']; 
     if ($name and $hobby ){ 
            echo json_encode('Data was succesfully captured');
         }else {
            echo json_encode('Data was not captured'); 
        }
    

    从 php 你必须以 json 的形式返回数据。

    还有js方面:

    $(document).ready(function(){ 
        $('#snd_btn').click(function() { 
            var name = $('#name').val(); 
            var hobby = $('#hobby').val();
            $.ajax({ 
                 url: "save.php", 
                 type: "POST", 
                 dataType: 'json', 
                 data: { name:name, hobby:hobby}  // data in { key : value}
                 success: function(result) { 
                 res = JSON.parse(res);
                 console.log(res);// display in developertools > console
                     $('#result').html(res); 
                 },
     }); }); });
    

    【讨论】:

    • 你的 ajax 数据不正确 $.ajax({ url: "save.php", type: "POST", dataType: 'json', data: { name:name, hobby:hobby}
    • 在 ajax 中你的数据语法不正确,数据应该在键值对中
    • 好的,我会检查并告诉你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2020-10-21
    • 2015-09-08
    相关资源
    最近更新 更多