2015-09-18 111 views
0

我正在研究需要將表單數據序列化爲JSON對象並將它們異步發送到使用AJAX的服務器(因爲服務器只接受JSON對象)的應用程序。有兩種形式來考慮:使用AJAX將JSON對象發送到服務器

frontend.html

<div class="login"> 

    <h>Login</h> 
    <form id="login_form_id" onsubmit="sign_in_client()"> 
     <label>Email: </label><input id="email0" type="email" name="l_email" required> 
     <br> 
     <label>Password: </label><input id="password0" type="password" name="l_password" required> 
     <br><br> 
     <input type="submit" value="Submit"> 
    </form> 

    </div> 

    <div class="signup"> 

    <h>Signup</h> 
     <form id="signup_form_id" onsubmit="sign_up_client()"> 
     <label>First Name: </label><input id="fname1" type="text" name="s_fname" required> 
     <br> 
     <label> Last Name: </label><input id="lname1" type="text" name="s_lname" required> 
     <br> 
     <label> City: </label><input id="city1" type="text" name="s_city" required> 
     <br> 
     <label> Country: </label><input id="country1" type="text" name="s_country" required> 
     <br> 
     <label> Male: </label><input id="gender1" type="radio" name="sex" value="male" required> 
     <br> 
     <label> Female: </label><input type="radio" name="sex" value="female" required> 
     <br> 
     <label> Email: </label><input id="email1" type="email" name="s_email" required> 
     <br> 
     <label> Password: </label><input id="password1" type="password" name="s_password" required> 
     <br> 
     <label> Repeat Pas: </label><input id="password2" type="password" name="s_rpassword" required> 
     <br> 
     <label> </label><input type="submit" value="Submit"> 
     </form>   

    </div> 

,處理表單輸入解析的代碼波紋管:

frontend.js

function sign_up_client() 
{ 
    var xmlhttp; 
    var fields = {}; 

    if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } 
    else 
     {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    xmlhttp.onreadystatechange=function() 
     { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
     document.getElementById("frontEnd").innerHTML=xmlhttp.responseText; 
     } 
     } 
    // Open connection to server asynchronously to the sign_up route function 
    xmlhttp.open("POST", "sign_up", true); 
    // Set the content type to JSON objects 
    xmlhttp.setRequestHeader("Content-type","application/json"); 
    // Send the form parameters needed for a sign-up operation 
    // Serialize them into a JSON object first 
    $("signup_form_id").find("input, textarea, select").each(function() { 
    var inputType = this.tagName.toUpperCase() === "INPUT" && this.type.toUpperCase(); 
    if (inputType !== "BUTTON" && inputType !== "SUBMIT") { 

    } 
    xmlhttp.send(inputType); 
    }); 

} 

的解析表單數據的代碼已從this問題中複製過來。我不清楚JSON對象是如何構建的。按鈕和提交類型是否包含在上面的例子中?輸入是否需要正確分析的形式(通過id)?

函數的末尾是inputType準備好發送正確的JSON對象的原因是什麼?

編輯#1:

frontend.html

<!DOCTYPE html> 
<html> 

<head> 

<link rel="stylesheet" type="text/css" href="client.css"> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<script type="text/javascript" src="client.js"></script> 
<script type="text/javascript" src="serverstub.js"></script> 


</head> 

<body> 

<div class="welcome"> 

    <img src="wimage.png" alt="Twidder Icon;" > 

    <div class="login"> 

    <h>Login</h> 
    <form id="signin_form_id" onsubmit="sign_in_client()"> 
     <label>Email: </label><input type="email" name="l_email" required> 
     <br> 
     <label>Password: </label><input id="password0" type="password" name="l_password" required> 
     <br><br> 
     <input type="submit" value="Submit"> 
    </form> 

    </div> 

    <div class="signup"> 

    <h>Signup</h> 
     <form onsubmit="sign_up_client()"> 
     <label>First Name: </label><input id="fname1" type="text" name="s_fname" required> 
     <br> 
     <label> Last Name: </label><input id="lname1" type="text" name="s_lname" required> 
     <br> 
     <label> City: </label><input id="city1" type="text" name="s_city" required> 
     <br> 
     <label> Country: </label><input id="country1" type="text" name="s_country" required> 
     <br> 
     <label> Male: </label><input id="gender1" type="radio" name="sex" value="male" required> 
     <br> 
     <label> Female: </label><input type="radio" name="sex" value="female" required> 
     <br> 
     <label> Email: </label><input id="email1" type="email" name="s_email" required> 
     <br> 
     <label> Password: </label><input id="password1" type="password" name="s_password" required> 
     <br> 
     <label> Repeat Pas: </label><input id="password2" type="password" name="s_rpassword" required> 
     <br> 
     <label> </label><input type="submit" value="Submit"> 
     </form>   

    </div> 

</div> 

</body> 
</html> 

frontend.js

function sign_up_client() 
{ 
    var xmlhttp; 
    var jsonObject = {}; 

    if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } 
    else 
     {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    xmlhttp.onreadystatechange=function() 
     { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
     } 
     } 
    // Open connection to server asynchronously towards the sign_up route function 
    xmlhttp.open("POST", "sign_in", true); 
    // Set the content type to JSON objects 
    xmlhttp.setRequestHeader("Content-type","application/json"); 
    // Send the form parameters needed for a sign-up operation 
    // Serialize them into a JSON object first 
    $("form").on("submit", function() { 
     var jsonObject = {}; 
     $(".signup").find("input, textarea, select").map(function(index, elem) { 
      //Ingore types such as button, submit and radio 
      elem.type.match(/button|submit|radio/i) === null && 
      (jsonObject[elem["name"]] = elem.value || "") 
      //If type = radio, grab the selected radio's value 
      elem.type.match(/radio/i) !== null && 
      elem.checked && (jsonObject[elem["name"]] = elem.value || "") 

     }); 

     alert (JSON.stringify(jsonObject, null, 4)); 
     return false; 
    }); 
    alert (JSON.stringify(jsonObject, null, 4)); 
    // Send the JSON object 
    xmlhttp.send(jsonObject); 
} 

function sign_in_client() 
{ 
    var xmlhttp; 
    var jsonObject = {}; 

    if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } 
    else 
     {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    xmlhttp.onreadystatechange=function() 
     { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
     } 
     } 
    // Open connection to server asynchronously towards the sign_up route function 
    xmlhttp.open("POST", "sign_in", true); 
    // Set the content type to JSON objects 
    xmlhttp.setRequestHeader("Content-type","application/json"); 
    // Send the form parameters needed for a sign-up operation 
    // Serialize them into a JSON object first 
    $("form").on("submit", function() { 
     var jsonObject = {}; 
     $(".login").find("input, textarea, select").map(function(index, elem) { 
      //Ingore types such as button, submit and radio 
      elem.type.match(/button|submit|radio/i) === null && 
      (jsonObject[elem["name"]] = elem.value || "") 
      //If type = radio, grab the selected radio's value 
      elem.type.match(/radio/i) !== null && 
      elem.checked && (jsonObject[elem["name"]] = elem.value || "") 

     }); 

     alert (JSON.stringify(jsonObject, null, 4)); 
     return false; 
    }); 
    alert (JSON.stringify(jsonObject, null, 4)); 
    // Send the JSON object 
    xmlhttp.send(jsonObject); 
} 
+0

首先,無論如何,使用jQuery中的'.ajax'。如果輸入類型是按鈕或提交,那麼你就有了入門的例子。 – lshettyl

+0

@ lshettyl所以輸入被忽略,如果它是按鈕或提交,但在這一點上的代碼是輸入一個JSON對象或不?它是否包含除按鈕和提交之外的所有輸入字段? – Sebi

+1

不,'inputType'是set => input,textarea中的最後一個匹配元素的tagName,select [ – lshettyl

回答

1

這裏是構建從表單字段JSON對象爲您的特定情況的快捷方式。

var o = {}; 
$(".signup").find("input, textarea, select").map(function(index, elem) { 
    //Ingore types such as button, submit and radio 
    elem.type.match(/button|submit|radio/i) === null && 
    (o[elem["name"]] = elem.value || "") 
    //If type = radio, grab the selected radio's value 
    elem.type.match(/radio/i) !== null && 
    elem.checked && (o[elem["name"]] = elem.value || "") 

}); 

現在,您可以發送o作爲您的JSON對象。

這裏是a demo相同。

+0

只是一個小問題:你可以通過id而不是它的容器指定完整的表單嗎? – Sebi

+0

只有在JavaScript代碼和html代碼都在同一個文件中時,此示例纔有效。我怎樣才能在一個單獨的html文件中引用一個表單。 http://jsfiddle.net/mvtafmj8/5/ – Sebi

+0

它應該在所有情況下工作,無論JS是否在同一個文件中。不要使用相同的ID倍數作爲ID是唯一的! – lshettyl

1

試試這個例子:

在下面的代碼中,使用了jQuery ajax語法,因爲它對我來說顯得更加簡單。要從表單域獲取值,使用serialize方法。

$('form').on('submit', sign_up_client); 
 
function sign_up_client(e) { 
 
    e.preventDefault(); 
 
    var formJson = []; 
 
    $(this).find(':input').each(function (index, elem) { 
 
     var inputType = this.tagName.toUpperCase() === "INPUT" && 
 
     var formObj = {}; 
 
     if (inputType === "RADIO") { 
 
      if ($(elem).is(":checked")) { 
 
       formObj[$(elem).attr('name')] = $(elem).val(); 
 
       formJson.push(formObj); 
 
      } 
 
     } 
 
     else if (inputType !== "BUTTON" && inputType !== "SUBMIT") 
 
      formObj[$(elem).attr('name')] = $(elem).val(); 
 
      formJson.push(formObj); 
 
     } 
 
    }); 
 
    $.ajax({ 
 
     type: "POST", 
 
     url: "test.php", 
 
     data: formJson, 
 
     dataType: "json", 
 
     success: function (data) { 
 
     }, 
 
     error: function() { 
 
      alert('error handing here'); 
 
     } 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="login"> 
 

 
    <h>Login</h> 
 
    <form id="login_form_id" method="post"> 
 
    <label>Email:</label> 
 
    <input id="email0" type="email" name="l_email" required> 
 
    <br> 
 
    <label>Password:</label> 
 
    <input id="password0" type="password" name="l_password" required> 
 
    <br> 
 
    <br> 
 
    <input type="submit" value="Submit"> 
 
    </form> 
 

 
</div> 
 

 
<div class="signup"> 
 

 
    <h>Signup</h> 
 
    <form id="signup_form_id" method="post"> 
 
    <label>First Name:</label> 
 
    <input id="fname1" type="text" name="s_fname" required> 
 
    <br> 
 
    <label>Last Name:</label> 
 
    <input id="lname1" type="text" name="s_lname" required> 
 
    <br> 
 
    <label>City:</label> 
 
    <input id="city1" type="text" name="s_city" required> 
 
    <br> 
 
    <label>Country:</label> 
 
    <input id="country1" type="text" name="s_country" required> 
 
    <br> 
 
    <label>Male:</label> 
 
    <input id="gender1" type="radio" name="sex" value="male" required> 
 
    <br> 
 
    <label>Female:</label> 
 
    <input type="radio" name="sex" value="female" required> 
 
    <br> 
 
    <label>Email:</label> 
 
    <input id="email1" type="email" name="s_email" required> 
 
    <br> 
 
    <label>Password:</label> 
 
    <input id="password1" type="password" name="s_password" required> 
 
    <br> 
 
    <label>Repeat Pas:</label> 
 
    <input id="password2" type="password" name="s_rpassword" required> 
 
    <br> 
 
    <label></label> 
 
    <input type="submit" value="Submit"> 
 
    </form> 
 

 
</div>

+2

'datastring'是一個字符串,OP想要發送一個'JSON'對象給服務器! – lshettyl

+1

@Rayin Dabre像@ lshettyl提到的那樣,最好是發送一個JSON對象而不是一個字符串。 – Sebi

+0

@Sebi,因爲我正在發送請求,所以OP可以在服務器端使用'$ _POST'訪問數據。如果有任何其他'json'數據的意圖,那麼它是有道理的.. – Rayon

相關問題