简体   繁体   English

使用javascript onload()和ajax来检索php数组

[英]using javascript onload() and ajax to retrieve php array

I'm using onload() and ajax to get the array from php, but it didnt work. 我正在使用onload()和ajax从php获取数组,但它没有用。 The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. html页面应该能够从n1.php和alert(“GOOD”)获取数组,但是它没有给出任何响应,甚至没有提示GOOD或BAD,所以我真的不知道代码有什么问题。 How can I fix this?? 我怎样才能解决这个问题??

n1.html: n1.html:

<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">             
function getArr(){              
    alert('return sent');   
    $.ajax({
        url: "n1.php",
        dataType: 'json',
        success: function(json_data){
        var data_array = $.parseJSON(json_data);
        var rec = data_array[0];
        alert("GOOD");
        },
        error: function() {
        alert("BAD");
        }
    });                 
}
 </script></html>

n1.php: n1.php:

<?php
    $output = array("cat","dog");
    echo json_encode($output);
?>

The request must contains the type of request. 请求必须包含请求的类型。 Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here. 此外,dataType指的是您要发送的数据,只要您不发送任何数据,此处就不需要。 Try this: 尝试这个:

$.ajax({
  url: "n1.php",
  type: "GET",
  success: function(json_data){
    var data_array = $.parseJSON(json_data);
    var rec = data_array[0];
    alert("GOOD");
  },
  error: function() {
    alert("BAD");
  }
});  

Try this 尝试这个

$.ajax({
  url: "n1.php",
  dataType: 'json',
  success: function(json_data){
    var data_array = json_data; // Do not parse json_data because dataType is 'json'
    var rec = data_array[0];
    alert("GOOD");
  },
  error: function() {
    alert("BAD");
  }
});

Now, two things to note here: 现在,有两点需要注意:

  1. You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs . 您还没有在ajax中传递HTTP方法,但默认情况下它是GETjQuery AJAX文档中所述 Please pass appropriate method type if it is not GET . 如果不是GET请传递适当的方法类型。

  2. Since you have sent dataType as 'json', you need not parse json received in the response in success handler. 由于您已将dataType作为'json'发送,因此无需在成功处理程序中解析响应中收到的json。

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

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