0

在我的 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:(示例.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);
?>
4

1 回答 1

1

您在“数据:数据”中设置的数据是您发送到 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");
        }
    });

    });

编辑:删除最后一个逗号,因为您的数组在那里结束。你可能想在输出之前设置一个标题。

<?php

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


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

    echo json_encode($advert);
?>
于 2013-07-23T19:52:05.103 回答