如何将 jQuery AJAX 与 PHP 一起使用


How do I use jQuery AJAX with PHP?

目前只是遇到了一个相当烦人的问题,如果有人能提供帮助,我会很高兴。

我正在看这个教程:https://www.youtube.com/watch?v=TR0gkGbMwW0,我决定试一试,看看它是否有效。但是,在我按文本字段中的域输入后,没有任何反应。

我的网页代码:

<html>
<head>
<title>TestingPage</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
</head>
<body>
<div id="userInput">
     What is the domain you would like to find the IP of? <input type="text" name="ip"        id="ipsearch"/>
     </div>
<script>
    $(document).ready(function() {
        $('#ipsearch').change(function() {
            $ajax({
                type: 'GET',
                url: process.php,
                data: 'ip=' + $('ipsearch').val(),
                success: function(msg) {
                    $('#userInput').html(msg);
                }
            });
        });
    }); //document.ready
</script>
</body>

</html>

我的PHP代码:

<?php
if ($_GET['ip']):
    $internetProtocol=gethostbyname($_GET['ip']);
    echo($internetProtocol);
endif;
?>

只是几个错别字。你有:

$ajax({
    type: 'GET',
    url: process.php,
    data: 'ip=' + $('ipsearch').val(),
    success: function(msg) {
        $('#userInput').html(msg);
    }
});

但是你需要(见评论(:

$.ajax({ // missing period ($ is jQuery, ajax() is the function)
    type: 'GET',
    url: 'process.php', // quotes around strings
    data: 'ip=' + $('#ipsearch').val(), // fix ID selector, missing '#'
    success: function (msg) {
        $('#userInput').html(msg);
    }
});

此外,由于缺乏更好的术语,您的PHP代码很丑陋,并且可能无法正常工作。这:

<?php
if ($_GET['ip']):
    $internetProtocol=gethostbyname($_GET['ip']);
    echo($internetProtocol);
endif;
?>

会更好,因为:

<?php
if (isset($_GET['ip'])) {
    $internetProtocol = gethostbyname($_GET['ip']);
    echo $internetProtocol;
}
?>

您缺少一些 ' ' 并且值选择器错误。 要调用 Ajax,您需要编写

$.ajax而不是$ajax

$(document).ready(function() {
    $('#ipsearch').change(function() {
        $.ajax({   //<<< period between $ and ajax
            type: 'GET',
            url: 'process.php', // <<< missing ' ' 
            data: 'ip=' + $('#ipsearch').val(),  //<<< missing #
            success: function(msg) {
                $('#userInput').html(msg);
            }
        });
    });
}); //document.ready