jQuery - send more data to Server by XML format


一般我們submit給server的資料,通常都是一筆的,可能為填寫表單後即送出。但是在

某些情況下,我們可否會submit多筆的資料給server呢?

剛好那時有寫一個大量新增地圖資料的功能,上傳後透過Server幫我先讀取Excel檔案裡面的

內容,並且response to client看是否有什麼問題(可能為這筆資料已新增),之後再做確認看是

否要新增進資料庫內。

在這裡我先寫一段jQuery的sample code,如下:

  1. var send_xml_data = null;
  2. send_xml_data = "<dataes>";
  3. send_xml_data += "<data><name>Ben</name><gender>男</gender></data>";
  4. send_xml_data += "<data><name>Mark</name><gender>男</gender></data>";
  5. send_xml_data += "</dataes>";
  6. $(document).ready(function() {
  7. $.ajax({
  8. type: 'POST',
  9. url: 'parser_sql.php?r='+Math.random(),
  10. processData: false,
  11. contentType: "text/xml",
  12. data: send_xml_data,
  13. dataType: 'text',
  14. success: function(text){
  15. alert(text);
  16. }
  17. });
  18. });

在這邊我自訂了XML Data準備要send to Server,請注意processData的attribute預設為true

,根據jQuery的官網說明是說

"If you want to send a DOMDocument, or other non-processed data, set this option to false."

因此我打破了原先的規則,選擇了自訂的DOM  data形式,所以請設為false

Server端的部分,我是用PHP code去接收send過來的資料,code如下:

  1. $rawdata = file_get_contents('php://input');
  2. $parse_xml = simplexml_load_string($rawdata);
  3. for($i = 0;$i < count($parse_xml->data); $i++){
  4. $data = $parse_xml->data[$i];
  5. echo $data->name."-".$data->gender."\n";
  6. }

您可以利用file_get_contents function來read the stream raw data,在此您就可以去parser

the XML data format,並且新增進資料庫內!本範例是response data to client,藉由alert

來達到我是否有成功傳送資料過去,並且將以text的資料格式讀取。

留言