简体   繁体   English

为什么我的AJAX收到请求失败

[英]why isn't my AJAX get request working

In my js page I want to get some variables from the php page using ajax(); 在我的js页面中,我想使用ajax()从php页面获取一些变量; This is all triggered by the html page load. 这都是由html页面加载触发的。 I've tried to use both GET and POST, but nothing alerts or logs to my console like it supposed to, not even the error. 我尝试同时使用GET和POST,但是没有像它应该的那样警告或记录到控制台,甚至没有错误。

HTML: 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) 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:

<?php

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

    echo json_encode($advert);
?>

the data you set at "data: data" ist the data u send to the php script. 您在“数据:数据”中设置的数据,以及您发送到php脚本的数据。 but u dont send any. 但你不发送任何。 the data you receive is available in you success function. 成功功能中将提供您收到的数据。 so print it. 所以打印出来。 plus i removed the alert. 再加上我删除了警报。 alerts are lame. 警报很la脚。 console rocks! 慰藉!

the " $(document).ready(" part starts your function as soon as your document is completlty loaded. i guess this is what you need and wanted there. 文档完全加载后,“ $(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: remove the last comma, as your array ends there. 编辑:删除最后一个逗号,因为数组在此结束。 you probably want to set a header before output. 您可能想在输出之前设置标题。

<?php

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


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

    echo json_encode($advert);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM