2013-07-23 52 views
0

在我的js页面中,我想使用ajax()从php页面获取一些变量; 这全部由html页面加载触发。我试图同时使用GET和POST,但没有任何警报或日志到我的控制台,就像它应该,甚至没有错误。为什么不是我的AJAX获取请求工作

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); 
?> 
+0

也许你还没有定义'data'了吗? – Blazemonger

+0

更重要的是,彻底删除'data'因为你似乎不在你的PHP文件中使用它 –

+0

sample.php实际输出任何事情?尝试在webbrowser中单独使用sample.php。如果你没有看到任何内容或内部服务器错误,那么它不是你的ajax调用。 – Bil1

回答

1

您在“data:data”设置的数据是您发送给php脚本的数据。但你不发送任何。您收到的数据在您的成功功能中可用。所以打印它。 加我删除了警报。警报是跛脚的。控制台岩石! 。

的“$(文件)。就绪(”部分,只要您的文档completlty加载启动的功能,我想这是你需要什么,并希望有

$(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); 
?> 
+0

您需要解释您做了什么。 –

+0

对不起,更正,我是一个新手... –

+0

谢谢你这工作,但为什么我需要添加标题? – Spilot