2009-01-20 63 views
0

我正在使用jQuery,JavaScript和PHP。我的Ajax.php文件只顯示 數據。文件test.php已將值分配給JavaScript函數。從PHP到JavaScript的值賦值

我的問題是我不能夠得到由test.php的分配值,從getList(data)

我的邏輯有問題嗎?我該怎麼做才能讓test.php分配的值顯示在getList()函數中?

$.ajax({ 
    type: 'POST', 
    url: 'ajax.php', 
    data: 'id=' + id , 
    success: function(data){ 
     $("#response").html(data); 
      if(flag != 0){ 
       flag = 0; 
       $.get("test.php", function(data){ 
        alert("Data Loaded: " + data); 
        getList(data); 
       }); 
      } 
     } //Success 
    }); //Ajax 

而test.php具有以下內容。

<?php 
    print "<script language='javascript'>"; 
    print " temp[temp.length]=new Array('STA-VES','East',4500);"; 
    print " temp[temp.length]=new Array('STA-CRF','West',5400);"; 
    print "</script>"; 
?> 

我的JavaScript函數有:

var temp=new Array(); 
getList(){ 
    alert(temp.length); 
    for(var i=0; i<temp.length; i++){ 
     var val = temp[i]; 
    } 
} 

回答

1

下面的代碼將輸出值您需要爲JSON的是重建的時候會類似於你的陣列:

<?php 
    echo json_encode(array(
     array(
      'STA-VES', 
      'East', 
      4500 
     ), 
     array(
      'STA-CRF', 
      'West', 
      5400 
     ) 
    )); 
?> 

然後,您的jQuery代碼可以將響應解析回JavaScript對象。

<?php 
    json_encode(array(
     array(
      'STA-VES', 
      'East', 
      4500 
     ), 
     array(
      'STA-CRF', 
      'West', 
      5400 
     ) 
    )); 
?> 

<script type="text/javascript"> 
    $.getJSON("test.php", function(json){ 
     // Access object 
     for(var i = 0; i < json.length; i++) { 
      alert(json[i][0]); 
      alert(json[i][1]); 
      alert(json[i][2]); 
     } 
    }); 
</script> 
0
$.get("test.php", function(data){ 
    alert("Data Loaded: " + data); 
    getList(data); 
}); 

你出現以下的輸出一個警告框?

 <?php 

     print "<script language='javascript'>"; 
     print " temp[temp.length]=new Array('STA-VES','East',4500);"; 
     print " temp[temp.length]=new Array('STA-CRF','West',5400);"; 
     print "</script>"; 

     ?> 

需要注意的是你應該得到的HTML(因爲這是你在你的PHP文件生成的東西。這不是從PHP數據傳遞到JavaScript的方式,除非你裝了這個PHP在iframe來直接操作父窗口的上下文。

你應該改變test.php的返回JSON。什麼是ajax.PHP回來呢?

+0

是我得到的警報,但功能的GetList顯示Willnot總lenghth – venkatachalam 2009-01-20 05:08:11