AJAX没有阅读PHP JSON echo

时间:2013-10-02 04:03:50

标签: php jquery ajax json

我有一个简单的jQuery AJAX请求,它将用户输入从文本框提交到PHP文件。这是代码:

$.ajax({
    url: url,
    type: type,
    data: data,
    dataType: 'json',
    success: function(response){
        console.log(response);
    }
});

PHP文件基本上记录了用户。一切正常,直到我向我的AJAX请求添加“dataType: 'json'”。现在,每当我点击我的提交按钮,没有任何记录。这是我的PHP文件:

<?php
include 'dbcon.php';

if ( isset( $_POST['text_login_username'], $_POST['text_login_password'] ) ) {
    $loginResult = array();
    $dbcon = getConnection();
    $userName = mysqli_real_escape_string( $dbcon, $_POST['text_login_username'] );
    $password = mysqli_real_escape_string( $dbcon, $_POST['text_login_password'] );
    $loginQuery = "SELECT * FROM userData WHERE userName='$userName' AND userPassword='$password'";
    $queryResult = mysqli_query( $dbcon, $loginQuery );
    $legalRows = mysqli_num_rows( $result );
    if ( $legalRows == 1 ) {
       $loginResult['allClear']=0;  
    } else {
       $loginResult['allClear']=1;
    }

    echo json_encode( $loginResult );
}
?>

AJAX文件

$(document).ready(function(){

$('form.loginSubmit').on('submit',function(){


    var that = $(this),
        url=that.attr('action'),
        type=that.attr('method'),
        data={};

    that.find('[name]').each(function(index,value){ 
        var that=$(this), 
            name=that.attr('name'); 
            value=that.val(); 
            data[name]=value;
    });


    $.ajax({
        url: url,
        type: type,
        data: data,
        contenType:'application/json; charset=utf-8',
        dataType:'json',
        success: function(response){
            console.log(response);
        },
        error: function(error)
        {
            console.log("test");
        }


    });

return false;

});


});

我可以确保正确设置正确的文件,帖子等链接,因为这一直有效,直到我尝试发送json_encode变量。任何帮助将不胜感激!

谢谢!

〜Carpetfizz

更新:我在我的AJAX调用中添加了error:设置,每当我提交时它都会运行。

更新:看看我的答案。这是我的解决方案。

5 个答案:

答案 0 :(得分:1)

检查此代码

<强> demo.php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1" />
<title>jQuery AJAX Call to PHP Script with JSON Return</title>
<style type="text/css">
body {font-family: Helvetica, Arial, sans-serif; font-size: 13px}
.the-return {background: #f0f0f0; padding: 10px; margin-top: 15px}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$("document").ready(function(){
    $(".js-ajax-php-json").submit(function(){
        var data = {
            "action": "test"
        };
        data = $(this).serialize() + "&" + $.param(data);
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "response.php",
            data: data,
            success: function(data) {
                $(".the-return").html(
                    "Favorite beverage: " + data["favorite_beverage"] + "<br />Favorite restaurant: " + data["favorite_restaurant"] + "<br />Gender: " + data["gender"] + "<br />JSON: " + data["json"]
                );

                alert("Form submitted successfully.\nReturned json: " + data["json"]);
            }
        });
        return false;
    });
});
</script>
</head>
<body>
<p><b>jQuery AJAX Call to PHP Script with JSON Return</b></p>
<form action="return.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
  <input type="text" name="favorite_beverage" value="" placeholder="Favorite restaurant" />
  <input type="text" name="favorite_restaurant" value="" placeholder="Favorite beverage" />
  <select name="gender">
    <option value="male">Male</option>
    <option value="female">Female</option>
  </select>
  <input type="submit" name="submit" value="Submit form"  />
</form>
<div class="the-return">
  [HTML is replaced when successful.]
</div>

</body>
</html>

<强> return.php

<?php
if (is_ajax()) {
    if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
        $action = $_POST["action"];
        switch($action) { //Switch case for value of action
            case "test": test(); break;
        }
    }
}

//Function to check if the request is an AJAX request
function is_ajax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test(){
    $return = $_POST;

    //Do what you need to do with the info. The following are some examples.
    //if ($return["favorite_beverage"] == ""){
    //  $return["favorite_beverage"] = "Coke";
    //}
    //$return["favorite_restaurant"] = "McDonald's";

    $return["json"] = json_encode($return);
    echo json_encode($return);
}
?>

答案 1 :(得分:1)

1.-在PHP代码中使用标题内容类型:

header('Content-type: application/json');

2.-在jQuery ajax代码中使用content-type标头:

contentType:'application/json; charset=utf-8'

3.-检查你的ajax jQuery代码是POST还是GET(默认:get):

type: "post"

4.-在PHP中打印JSON:

if( array_key_exists("text_login_username",$_POST) AND array_key_exists("text_login_password",$_POST) )
{
    header('Content-type: application/json');
    /**
    *   Create link
    */
    $link = getConnection(); /* user function */
    /**
    * Default value for result
    */
    $result = array(
        "allClear"  =>  1
    );
    /**
    *   first arg is connection
    *   mysqli_real_escape_string ( mysqli $link , string $escapestr )
    */
    $username = mysqli_real_escape_string( $link , $_POST["text_login_username"] );
    $password = mysqli_real_escape_string( $link , $_POST["text_login_password"] );

    /**
    *   Select "1" is best way with LIMIT; you dont need all fields... ¬¬ bad way...
    **/
    $source = mysqli_query( $link , "SELECT 1 FROM userData WHERE userData.userName='$username' AND userData.userPassword='$password' LIMIT 1" , MYSQLI_STORE_RESULT  );
    /**
    * count
    */
    if( mysqli_num_rows( $source ) == 1 )
    {
        $result["allClear"] = 0;
    }
    /**
    *   print json
    */
    echo json_encode( $result );
    /**
    *   prevent others prints
    */
    exit;
}

5.-使用 array_key_exists 来验证数组中是否存在密钥

bool array_key_exists( mixed $key , array $search )

6.-使用此 $。ajax 代码:

$.ajax({
    url: "json.php",
    type: "post",
    data: {
        text_login_username  : "xxxx",
        text_login_password  : "xxx"
    },
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(response)
    {
        console.log(response);
    }
});

祝你好运!

答案 2 :(得分:0)

试试这个。确保JS中的数据变量具有JS对象的正确语法。有关JSON objects here

的更多信息
$.ajax({
    url: url,
    type: type,
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(response){
        console.log(response);
    }
});

答案 3 :(得分:0)

你能试试吗?添加到您的服务器脚本。

我的json_encode也没有返回任何内容,直到我升级我的PHP版本时添加了这个。它与json_encode有关,仅适用于UTF-8

mysqli_query($dbcon, "SET NAMES utf8"); 

我还将此添加到脚本的顶部...

mb_internal_encoding("UTF-8");

答案 4 :(得分:-2)

解决方案很奇怪。 mysqli_num_rows出了问题。我只是这样做了。

$legalRows=$queryResult->num_rows;

工作正常。感谢所有的好答案。我肯定学到了一些我将要实施的新东西。