2012-10-31 39 views
-4

嗨我搜索很多從PHP返回得到一個迴應,如果這個迴應是好的做一些事情,如果它的假做別的事情(!!!!!!!!當我有其他的輸出PHP的!!!!! !) 這是我的索引文件這個json必須工作嗎?

<head> 
<script src="jquery-1.7.2.js" type="text/javascript"></script> 
<script src="js.js" type="text/javascript"></script> 
</head> 
<body> 
<p> click </p> 
<input type="text" id="who"> 
<br> 
<input type="text" id="why"> 
<div id="bg" align="center"> 
</div> 
</body> 

這是我的JS文件

$(document).ready(function(){ 
    $('p').click(function(){ 
     var who = $('input#who').val(); 
     var why = $('input#why').val();  
     $.post('file.php',{who:who,why:why},function(data) { 
    if(data.success){ 
     alert(data.message); 
    } 
    else{ alert('ERROR:' + data.message); 
    } 
}); 




    }); 
}); 

,這是我的file.php

<?php 
$response = array('success' => 'true', 
    'code' => "jQuery('#bg').html('\"Javascript\", \"json\", \"PHP\"');"); 
echo json_encode($response); 
?> 

我的問題: 1 - 這是爲什麼不工作,我得到警報(錯誤:undifined) 2 - 我如何從php文件得到一些結果,當它有其他的輸出 這樣的:

<?php 
echo "1"; 
echo "2"; 
echo "3"; 
and now echo that json 
?> 

感謝:(

+1

omg man。通常最好在最後放一個笑臉。 :) – DarthVader

+0

'data.success'應該至少工作,儘管'alert(data.message)'將失敗,因爲數據中沒有「消息」。嘗試從PHP文件發送一個'Content-type:application/json'頭文件。 –

回答

3

why this is not work i get alert (error:undifined)

你必須告訴jQuery響應是JSON。您可以通過傳遞'json'作爲第四參數如願$.post[docs]或由PHP設置正確的響應頭:

header('Content-Type: application/json'); 

或者你可以分析自己與jQuery.parseJSON[docs]響應。

how i can get some result from that php file when its have other output like this

有沒有簡單的方法。該響應不再有效,因此您必須以某種方式自己解析它。你應該避免這樣做,並返回所有的JSON。

+0

'你必須告訴jQuery'。呃不,你沒有明確告訴它是什麼,它猜測數據類型;這個問題實際上是在JSON前面的'「123」:) –

+0

@Jack:我不認爲jQuery試圖猜測內容類型是否設置爲HTML。至少這是很多問題的根源。響應中的無效數據是第二個問題,與第一個問題無關。 –