[英]Handle php which get ajax json request
假設我運行了這個ajax-
$.ajax({
url: "index.php",
type: 'POST',
data :{test : 123}, //updated due to the approved answer
dataType: 'json'
});
我想在它的json的內容- index.php
,並alert
其test
值(平均得到- 123
),
我試過了-
index.php-
<?php
$json = $_POST["test"];
echo '<script>';
echo 'alert('+$json+');';
echo '</script>';
?>
但是沒有任何警報。
如何正確處理?
更新:
在@JayBlanchard評論之后,
$json = $_POST["test"]
真的得到test
值嗎?
alert
對我來說並不重要,我只想確保在PHP方面是否正確解析了alert
,這意味着將123
返回客戶端 。
您需要在JavaScript回調中處理來自php的結果。 因此,您可以這樣做:
$.ajax({
url: "index.php",
type: 'POST',
data :{text : 123},
dataType: 'json',
complete: function(data){
console.log(data.responseText) //(not sure why responseText is necessary)
}
});
你的PHP將是這樣的:
<?php
$json = $_POST["text"];
echo $json;
?>
您只需在success
回調中執行此操作:
$.ajax({
url: 'index.php',
type: 'post',
data: {text : 123},
dataType: 'json',
success: function(data) {
alert(data.test);
}
});
和你的index.php
:
<?php
echo json_encode(array('test' => $_POST['test']));
?>
您必須定義一個javascript函數來處理響應:
var handle_response = function(data_from_server, StatusText, jqxhr) {
// check http://api.jquery.com/jquery.ajax/ for StatusText and jqxhr meaning.
alert(data_from_server);
}
那你叫你的ajax
$.ajax({
url: "index.php",
type: 'POST',
data :{text : 123},
dataType: 'json',
success: handle_response
});
你的PHP將是這樣的
<?php
$json = json_decode($_POST["text"]); // not sure about dataType: 'json'
echo "this is coming from php on server ";
?>
如果要執行從服務器創建的某些腳本,請查閱jquery手冊以安全地進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.