1

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

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

PHP 文件基本上将用户登录。在我将“ dataType: 'json'”添加到我的 AJAX 请求之前,一切正常。现在,每当我单击提交按钮时,都没有记录。这是我的 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变量之前有效。任何帮助将非常感激!

谢谢!

~地毯嘶嘶声

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

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

4

5 回答 5

1

检查此代码

演示.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>

返回.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);
}
?>
于 2013-10-02T04:47:35.963 回答
1

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

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

2.- 在您的 jQuery ajax 代码中使用内容类型标头:

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);
    }
});

祝你好运!

于 2013-10-02T05:18:13.003 回答
0

尝试这个。确保 JS 中的数据变量具有 JS 对象的正确语法。有关 JSON 对象的更多信息在这里

$.ajax({
    url: url,
    type: type,
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(response){
        console.log(response);
    }
});
于 2013-10-02T04:52:13.383 回答
0

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

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

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

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

mb_internal_encoding("UTF-8");
于 2013-10-02T05:12:49.900 回答
-2

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

$legalRows=$queryResult->num_rows;

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

于 2013-10-02T05:26:11.563 回答