2016-03-04 43 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')}); 
});