PHPコード(同じページに送信する場合)は、ページ全体の内容が応答データに返されないように注意する必要があります。そのために、私は次のようなアプローチを使用する傾向がある - それは、文書
<?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の出力バッファをクリアすることでob_clean
が有用であるが、URLを必要とする - あなたと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>
あなた 'doesnの$ .ajax'; tは'持っurl'、それは@MilanChheda I'veは、あなたがそれを置くいけない場合、デフォルトのオプションであることを読ん –
欠けていますあなたの同じページ。これは間違っていますか? – JuanjoC
うーん、あなたは正しい@JuanjoC、私のミスです。 –