[英]Save data asynchronously php
今天我的一個客戶要求他需要在更改時異步地將表單數據保存到服務器
例如:
我有一個填寫用戶詳細信息的表單,包括文本框,選擇,收音機,支票等...
所以當我在文本框中更改值時,我需要將它們保存回服務器。
我可以使用PHP上的任何庫或東西嗎?
請注意我知道什么是ajax,但我仍然需要手動編寫代碼,我還需要重新使用。 這就是我要求圖書館的原因。
編輯
我知道jQuery,Js,Ajax等。但我的想法不同......
比如說
<input type="text" class="dataBinder[name]" id="cname" name="name" />
<input type="checkbox" class="dataBinder[agree_me]" id="agree_me" name="agree_me" />
我相信我能做到
$("#cname").event(function(){
var is_changed = true; ///check for changes if any
if(is_changed)
{
//send to the server
}
});
但我正在尋找一個可以自動完成的圖書館
例如:
//assume a library dataMapper
var myForm = $("#myForm"); //get the form
myForm.dataMapper({
"server" :"serverUrl/someFunc.php"
//may be some other kind of option too
});
someFunc.php在服務器上
dataMapper DM = new dataMapper();
$changes = DM->get_data(); //a function that which give the changes
return $changes
值來自dataBinder[name]
<input type="text" class="dataBinder[name]" id="cname" name="name" />
var_dump($changes);
給
array(3) {
["changes"]=>
array(2) {
["cname"]=>
string(15) "my-changed-name"
["agree"]=>
bool(false)
}
["time"]=>
string(6) "720124"
["form"]=>
string(6) "formId"
}
我相信可能有很多關於開發人員的問題,但我只是在搜索,因為我不想重新發明輪子。
為什么不在所需的每個輸入元素中使用data-save-ajax屬性,並將ajax頁面添加為值。 現在,您創建一個jQuery(或您喜歡的任何ajax javascript)並編寫一個將值保存到data-save-ajax鏈接的on-change事件處理程序。
像這樣的東西:
jQuery("[data-save-ajax]").change( function() {
jQuery.ajax({
url: jQuery(this).attr("data-save-ajax"),
method: 'post',
data: {
newvalue: jQuery(this).val()
}
});
});
要考慮的是這將產生的負載。 最好是在失去焦點時使用事件處理程序。 或者如果你喜歡改變,那么在開始改變之前可能還需要幾毫秒。
data-save-ajax鏈接將是一個php頁面,它檢查會話並根據url將數據保存到數據庫。 您可以使用.htaccess(或其他)重寫來讓您的php知道您正在使用的輸入。
例如, /ajax/text/name
的data-save-ajax url將被重寫為/ajax/index.php
。
我曾經寫過像這樣的ajax更新程序,它很容易構建,你可以隨時隨地更新或重新使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.