AJAX返回false但我不明白为什么?

时间:2013-04-24 18:15:44

标签: php javascript ajax

我正在尝试立即对输入更改的关键字进行数据库查询。现在,我得到了一个成功的查询,并存储了所有结果,但是在GET上显示它们,ajax函数返回false。为什么这样做?

控制台输出:

POST http://example.com/functions/ajax.php

response: the data i need to display

后跟

GET http://example.com/functions/ajax.php

response: false

这是我的JS:

<script id="source" language="javascript" type="text/javascript">
$(function () {
    $('#url').bind('input', function () {
        $(this).val() // get  value
        $.ajax({
            type: 'POST',
            url: 'functions/ajax.php',
            data: {
                url: $('#url').val()
            },
            success: function (data) //on receive of reply
            {
                $(function () {

                    $.ajax({
                        url: 'functions/ajax.php', //the script to call to get data          
                        data: "", //you can insert url arguments here to pass to api.php
                        //for example "id=5&parent=6"
                        dataType: 'json', //data format      
                        success: function (data) //on receive of reply
                        {
                            var namePHP = data[1];
                            var categoryPHP = data[2];

                            //--------------------------------------------------------------------
                            // 3) Update html content
                            //--------------------------------------------------------------------

                            $('#name').html(namePHP); // # name and #category are input fields I want autofilled
                            $('#category').html(categoryPHP);


                        }
                    });
                });
            }
        });
    });
});
</script>

ajax.php

<?php
require_once ('DBconnect.php');

$url = $_POST['url'];

$url = mysqli_real_escape_string($con, $url);

$query = "SELECT * FROM `inserted_posts` WHERE `search_name` = '$url'";
$result = mysql_query($query);

$array = mysql_fetch_array($result);

echo json_encode($array);
?>

2 个答案:

答案 0 :(得分:1)

您的ajax.php文件依赖于$_POST个变量。这意味着您必须使用POST方法发送数据。否则,PHP就是看不到它。

答案 1 :(得分:0)

将$ url的变量赋值更改为从$ _REQUEST而不是$ _POST

$url = $_POST['url'];

$url = $_REQUEST['url'];