2016-03-04 42 views
1

我有一個輸入框簡單的div來插入數據球隊數據jQuery的AJAX不及格「POST」數據

<div> 
     <label>Register</label> 
     <input type="text" name="nt" placeholder="Team Name"> 
     <label>Team</label> 
     <input type="text" name="n1" placeholder="Steam username"> 
     <input type="text" name="n2" placeholder="Steam username"> 
     <input type="text" name="n3" placeholder="Steam username"> 
     <input type="text" name="n4" placeholder="Steam username"> 
     <input type="submit" id="sbutton"></input> 
    </div> 

然後使用jQuery來收集數據並將其發送到我的PHP文件。

$('#sbutton').click(function(){ 
     var sdata=[]; 
     $(this).parent().children("input[type=text]").each(function(index,value){ 
      index = $(this).attr("name"); 
      value = $(this).val(); 
      sdata[index]=value; 
     }); 
     console.log(sdata); 
     $.post('php/team.php',sdata, 
      function(returnedData){ 
       console.log(returnedData); 
     }); 
    }); 

在我的PHP文件,我處理這些數據,但問題是,不是由jquery的function.My PHP傳遞:

<?php 
session_start(); 
include_once "functions.php"; 
print_r($_POST); 
if(!isset($_POST["nt"])) die("Usernames not set");?> 

我的控制檯日誌:

[nt: "asdasd", n1: "asdasd", n2: "asdasd", n3: "asdasd", n4: "asdasd"] 
jquery-2.1.4.min.js:4 XHR finished loading: POST 
"http://localhost/tournament/php/team.php".k.cors.a.crossDomain.send 
@ jquery-2.1.4.min.js:4n.extend.ajax @ jquery-2.1.4.min.js:4n 
(anonymousfunction) @ jquery-2.1.4.min.js:4(anonymous function) @ main_page.php:31n.event.dispatch @ jquery-2.1.4.min.js:3r.handle @ jquery-2.1.4.min.js:3 
main_page.php:33 Array 
(
) 
Usernames not set 

這是怎麼發生的?

回答

1

常與輸入的名稱對象電子爲對象,並設置屬性名稱由整株$_POST使用你目前正在使用

$('#sbutton').click(function(){ 
    var sdata={}; 
    $(this).parent().children("input[type=text]").each(function(index,value){ 

     sdata[this.name]=this.value; 
    }); 
    console.log(sdata); 
    $.post('php/team.php',sdata, 
     function(returnedData){ 
      console.log(returnedData); 
    }).fail(function(){alert('Ooops something wrong')}); 
}); 

你可以看到什麼是收到了非常方便的在同一PHP的做法,它會出現在控制檯日誌你的成功經理。

echo json_encode($_POST);exit; 
+0

謝謝你工作好:) – August

0

只需更換

// dictionary, i.e. sdata["nt"] would not work 
var sdata=[]; 

通過

// dictionary, i.e. sdata["nt"] would work 
var sdata={}; 

JQuery的您傳遞

的數據使用JSON.stringify方法,如果您有疑問,嘗試使用

console.log(JSON.stringify(sdata)) 
1

你也可以利用FORMDATA對象,像這樣的,即使你沒有出現有<form>定義在你HTML

的FORMDATA對象讓你編一套關鍵的/值對使用XMLHttpRequest發送。它主要用於發送表單數據,但可以獨立使用表單來傳輸鍵控數據。如果表單的編碼類型設置爲multipart/form-data,則傳輸的數據格式與表單的submit()方法用於發送數據的格式相同。

$('#sbutton').click(function(){ 
    var formData = new FormData(); 

    $(this).parent().children("input[type=text]").each(function(index,value){ 
     formDate.append($(this).attr("name"), $(this).val()); 
    }); 
    $.post('php/team.php',formData, 
      function(returnedData){ 
       console.log(returnedData); 
      }) 
      .fail(function(){alert('Ooops something wrong')}); 
});