为什么不是';t我的AJAX获取请求工作


why isn't my AJAX get request working

在我的js页面中,我想使用ajax()从php页面获取一些变量;这一切都是由html页面加载触发的。我尝试过同时使用GET和POST,但没有任何东西像它应该的那样提醒或记录到我的控制台,甚至没有错误。

HTML:

<!DOCTYPE html>
<html>
    <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
   <script src="http://XXXXXX/bn/sample.js"></script>
    </head>
    <body>
        <div>Welcome! </div>
    </body>
</html>

JS:(sample.JS)

$(function(){
 $.ajax({
        url : "http://XXXXXX/bn/sample.php",
        type : 'GET',
        data : data,
        dataType : 'json',
        success : function (result) {
           alert(result.ajax); // "Hello world!" should be alerted
           console.log(result.advert); 
        },
        error : function () {
           alert("error");
        }
    });
    });

PHP:

<?php
    $advert = array(
        'ajax' => 'Hello world!',
        'advert' => 'Working',
     );
    echo json_encode($advert);
?>

您在"data:data"处设置的数据是您发送到php脚本的数据。但是你一个也不寄。您收到的数据在您的成功功能中可用。所以打印出来。此外,我删除了警报。警报是站不住脚的。控制台震动!

"$(document).ready()"部分在您的文档完全加载后立即启动您的功能。我想这正是您所需要和想要的。

$(document).ready(function() {    
 $.ajax({
        url : "http://XXXXXX/bn/sample.php",
        type : 'GET',
        data : (),
        dataType : 'json',
        success : function (data) {
           console.log(data.advert); 
        },
        error : function () {
           console.log("error");
        }
    });
    });

edit:删除最后一个逗号,因为数组到此为止。您可能希望在输出之前设置一个标头。

<?php
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');

    $advert = array(
        'ajax' => 'Hello world!',
        'advert' => 'Working'
     );
    echo json_encode($advert);
?>