簡體   English   中英

如何將 HTML 表單數據作為 JSON 發送到端點 http://localhost:8080

[英]How to send HTML form data as JSON to endpoint http://localhost:8080

我有一個簡單的 HTML 表單和一個使用數據生成 JSON 的 Java Script 函數。 我現在需要的只是將它發送到端點“ http://localhost:8080 ”並檢查 JSON 是否到達那里。 到目前為止,我得到了這個:

 function create_send_Json(){ // get name var fname = document.forms["myForm"]["first_name"].value; var lname = document.forms["myForm"]["last_name"].value; // make JSON data = { "fname": fname, "lname": lname}; var jsonData = JSON.stringify(data); // Send data var xhr = new XMLHttpRequest(); var url = 'http://localhost:8080'; xhr.open("POST", url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(jsonData); return false; }
 <html> <head> <title>Form</title> <script type = "text/javascript" src = "action.js" ></script> </head> <body> <form onsubmit="return create_send_Json();" name="myForm"> <p><label for="first_name">First Name:</label> <input type="text" name="first_name" id="fname"></p> <p><label for="last_name">Last Name:</label> <input type="text" name="last_name" id="lname"></p> <input value="Submit" type="submit" onclick="submitform()"> </form> </body> </html>

但我認為這是行不通的。

提前致謝。

- - - 編輯 - - - - -

為了清楚起見,我使用以下內容來檢查它是否有效:

alert('status: '+xhr.status + ' ,readyState: '+xhr.readyState);

並收到

status: 0 ,readyState: 1

此外,我在代碼中進行了建議的更改,但仍需要檢查另一端是否收到了 json。

解決方案:

在 HTML sumbit 按鈕中用 create_send_Json 替換 submitform。

在提交按鈕而不是表單中添加提交事件。 改變它,你會很高興去。

function create_send_Json(){

    // get name
    var fname = document.forms["myForm"]["first_name"].value;
    var lname = document.forms["myForm"]["last_name"].value;

    // make JSON
    data = { "fname": fname, "lname": lname};
    var jsonData = JSON.stringify(data);

    // Send data
    var xhr = new XMLHttpRequest(); 
    var url = 'http://localhost:8080';

    xhr.open("POST", url); 
    xhr.setRequestHeader("Content-Type", "application/json"); 
    xhr.send(jsonData);

    return false;
}

    <html>
        <head>
            <title>Form</title>
            <script type = "text/javascript" src = "action.js" ></script>
        </head>
    <body>
        <form name="myForm" action="POST">
            <p><label for="first_name">First Name:</label>
            <input type="text" name="first_name" id="fname"></p>

            <p><label for="last_name">Last Name:</label>
            <input type="text" name="last_name" id="lname"></p>

            <input value="Submit" type="submit" onclick="create_send_Json()">
        </form>
    </body>
    </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM