PHP代碼(發送到同一頁面時)需要特別注意,以免整個頁面內容在響應數據中返回。爲此我傾向於用下面的辦法 - ob_clean
是有用的,它會清除生成到該點的文件
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['ucli'])){
/*
Prevent other page content prior to this point
being included in whatever response is sent by
clearing the output buffer
*/
ob_clean();
/* Capture post variable */
$ucli = filter_input(INPUT_POST, 'ucli', FILTER_SANITIZE_STRING);
/* Do stuff */
/* send response */
echo $ucli;
/*
Immediately terminate from this portion of code so that
the only response sent is what you determine above
*/
exit();
}
?>
Ajax的功能在任何HTML的輸出緩衝器需要一個網址 - 你正嘗試將POST請求發送到您可以使用location.href
的同一頁面。回調(成功)函數應該處理響應,而在它看起來它正在處理髮送的數據之前。
$(function(){
$('#ucli').on('input', function() {
var client = $('input[name="ucli"]').val();
var dataString = 'ucli=' + client;
$.ajax({
url: location.href,
type: 'POST',
data: dataString,
success: function(response){
$('ucli').html(response);
},
error: function(err){
alert(err)
}
});
});
});
整版例如
<!doctype html>
<html>
<head>
<title>jQuery</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(function(){
$('#ucli').on('input', function() {
var client = $('input[name="ucli"]').val();
var dataString = 'ucli=' + client;
$.ajax({
url: location.href,
type: 'POST',
data: dataString,
success: function(response){
$('#result').html(response);
},
error: function(err){
alert(err)
}
});
});
});
</script>
</head>
<body>
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['ucli'])){
/*
Prevent other page content prior to this point
being included in whatever response is sent by
clearing the output buffer
*/
ob_clean();
/* Capture post variable */
$ucli = filter_input(INPUT_POST, 'ucli', FILTER_SANITIZE_STRING);
/* Do stuff */
/* send response */
echo $ucli;
/*
Immediately terminate from this portion of code so that
the only response sent is what you determine above
*/
exit();
}
?>
<form name='jqt' method='post'>
ucli:<input type='text' name='ucli' id='ucli' />
<div id='result'></div>
</form>
</body>
</html>
你'$ .ajax'沒有按;噸有'url',唯一缺少 –
@MilanChheda從來就讀取,如果你不把它的默認選項爲你的同一頁。這是錯的嗎? – JuanjoC
嗯,你是對的@JuanjoC,我的小姐。 –