【问题标题】:why isn't my AJAX get request working为什么我的 AJAX 获取请求不起作用
【发布时间】:2013-07-23 01:36:29
【问题描述】:

在我的 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 文件中使用它
  • sample.php 真的有输出吗?尝试在网络浏览器中自行访问 sample.php。如果您什么也没看到或内部服务器错误,那么这不是您的 ajax 调用。
  • 然后检查 Chrome 控制台或 Firebug 会发生什么..

标签: php jquery post get xmlhttprequest


【解决方案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);
?>

【讨论】:

  • 你需要解释你做了什么。
  • 您正在使用 json 文件类型,但用于生成它的文件是 php 文件。标头告诉您的脚本它正在处理请求的 json 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 2020-08-12
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多