我正在向php文件发送一个ajax请求,我将在其中更新数据库,并根据我的条件选择一个值。但是如何在 ajax 回调中返回该$variable并在输入文本框中显示它。
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
}
});
我的 PHP 文件是
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['id']==2) //taking
{
$book_id = $_GET['bookid'];
$startdate = $_GET['startdate'];
$update_validity = "UPDATE booking SET valid = '2',start_date_timestamp = '$startdate' where book_id = '$book_id'";
$query = mysql_query($update_validity);
if($query==TRUE)
{
$get_select_query = "select start_date_timestamp from booking where book_id = '$book_id'";
$get_query = mysql_query($get_select_query);
$row = mysql_fetch_assoc(get_query);
$startdate_return = $row['start_date_timestamp'];
echo $startdate_return;
}
}
?>
你应该使用 json 格式,如下所示:
在您的 PHP 文件中
$arrFromDb = array(
'id' => 1,
'bookName' => 'Da Vinci Code'
)
echo json_encode( $arrFromDb ); exit();
在你脚本中
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
var book = $.parseJSON(data) // now book is a javascript object
var bookName = book.bookName;
}
});
我希望这对你有帮助
在页面中创建一个元素,如<span>
,并为其提供唯一的 ID,如 <span id="testspan"></span>
。这是显示文本的位置。然后在你的JS中;
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
$( "#testspan" ).html(result);
}
});
只需echo
您的 php 文件中,输出(而不是被浏览器显示为默认 PHP 页面(将在 JS 中可用,作为 ajax 调用的结果 ( data
(
尝试使用 val((,
.HTML
<input type="text" id="inputId" />
Js
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
$( "#inputId" ).val(data);
}
});
PHP代码
<?php
echo $bookid= isset($_REQUEST['bookid']) ? $_REQUEST['bookid'] : "No bookid";
// you can use $_GET for get method and $_POST for post method of ajax call
return
?>
In updatenewuser.php
//after all operations
echo $variable_to_pass;
然后在 ajax 请求中:
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
alert(result);//result will be the value of variable returned.
$("#input_box").val(result); //jquery
document.getElementById("input_box").value = result; // Javascript way
}
});
HTML 是 :
<input type="text" id="input_box" value=""/>
干杯