要使用jQuery的讓 Ajax請求,你可以做到這一點通過下面的代碼
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
的JavaScript:
方法1
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
方法2
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
/* I am not aborting previous request because It's an asynchronous request, meaning
Once it's sent it's out there. but in case you want to abort it you can do it by
abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* request cab be abort by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function(){
// show error
$("#result").html('There is error while submit');
});
的.success()
,.error()
,和.complete()
回調棄用的jQuery的1.8。要準備代碼以進行最終刪除,請改用.done()
,.fail()
和.always()
。
MDN: abort()
。如果請求已經發送,則此方法將中止請求。
所以我們現在已經成功地發送ajax請求來抓取數據到服務器。
PHP
正如我們使AJAX調用(type: "post"
)POST請求,我們現在可以使用兩種$_REQUEST
或$_POST
$bar = $_POST['bar']
你也可以看到你在POST請求得到獲取數據通過簡單地,Btw確保$ _POST設置其他明智你會得到錯誤。
var_dump($_POST);
// or
print_r($_POST);
而且要插入值數據庫確保您致敏或逃逸,最好將使用預處理語句所有請求(天氣,你做GET或POST)進行查詢之前正常。
如果你想返回任何數據返回頁面,你可以通過如下回顯數據來做到這一點。
// 1. Without JSON
echo "hello this is one"
// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));
,比你能得到它像
ajaxRequest.done(function (response){
alert(response);
});
還有的Shorthand Methods夫婦可以使用下面的代碼它做同樣的工作。
var ajaxRequest= $.post("test.php",values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
請參閱[相關元討論](http://meta.stackexchange.com/q/161943/147191)推斷undeletion背後的推理。 – TRiG 2013-01-08 13:14:16
最佳答案在這裏: http://stackoverflow.com/questions/19029703/jquery-using-ajax-to-send-data-and-save-in-php/19029778#19029778 檢查,測試工作 – rohitcopyright 2013-09-26 16:16:18