dongshuang0011 2015-04-13 22:34
浏览 33
已采纳

需要通过json格式的javascript发送数据到服务器[关闭]

I am having trouble posting my data from a form to the server but must be in json format and using ajax. How do I do this while using javascript & cannot use Jquery. Here my questions...

Also Thanks in Advance!

  • How do I convert it and send it to the server with handling HTTP 200 success and using ajax?

  • On return of a JSON object with the status encoded like so: {"status":"---"}, where "---" is either "success" or "error".

  • If the response status is success, a thank you message should be displayed.
  • If the response status is error, the page should display a general warning such as 'request could not be completed'.

    HTML

    Contact Me

    <form id="contactus" action="http://wirehoer.net" method="post">
    <fieldset>
        <!-- Contact Name
         -->
        <label for="name">Name:</label>
        <input name="name" id="name" type="text" pattern="\b[-'a-zA-Z]+,?\s[-'a-zA-Z]{0,19}\b" autofocus required>
        <span id="name-error" class="error">Please enter first & last name</span>
        <!-- Email 
        -->
        <label for="email">Email:</label>
        <input name="email" id="email" type="email" pattern="^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" required>
        <span id="email-error" class="error">Please enter email address</span>
        <!-- Phone 
        -->
        <label for="phone">Phone:</label>
        <input name="phone" id="phone" type="tel" pattern="\d{10}" required>
        <span id="phone-error" class="error">Phone number must only contain numbers</span>
        <!-- Status - Client | Partner | Vendor 
        -->
        <label for="status">Status:         
            <select name="status" id="status">
                <option value="client">Client</option>
                <option value="partner">Partner</option>
                <option value="vendor">Vendor</option>
            </select>
        </label>
        <!-- Subscribe 
        -->
        <label for="subscribe">
        <input name="newsletter" id="subscribe" type="checkbox" value="on" checked>
            Send me your newsletter</label>
        <!-- Support - Sales | Support 
        -->
        <label class="needs" for="select_sales">
            <input id="select_sales" name="slsSelect" type="radio" value="sales" checked>Sales
        </label>
        <label class="needs" for="select_support">      
            <input id="select_support" name="slsSelect" type="radio" value="support">Support
        </label>
        <!-- Description 
        -->
        <label for="details">Message:</label>
        <textarea name="message" id="details" rows="10" cols="30"></textarea>
        <span id="details-error" class="error">Please describe what your request is</span>
    </fieldset>
    
    <fieldset>
        <button id= "send" type="submit">Send</button>
        <button type="reset">Reset</button>
    </fieldset>
    </form>
    <!-- javascript validation 
    -->
    <script type="text/javascript" src="contactform_Lab11.js"></script>
    
    </body>
    </html> 
    

Javascript

> //This will get the data of the fields
> document.getElementById('send').onclick=function(evt) {
> 
> var errors = false; //Gets all the inputs from contact form var
> myNodeList = document.querySelectorAll('input, textarea, select');
> 
> //Declar the vars //var i, val; // empty Array
> 
> //Start of loop  for (i = 0; i < myNodeList.length; i++) {
>     // Get element
>     val = myNodeList[i];
> 
>     //Get pattern attribute of regEx
>     regEx = new RegExp(val.getAttribute("pattern"));
> 
>     //Get Error message
>     err = document.getElementById(val.id+"-error")
> 
>     //By default, set the class to error, which hides the error message
>             err.className="error";
> 
>     //Test value "val" again the regEx
>     if(!regEx.test(val.value)){
>         //input fails and does not pass regEx test, set .display class
>         err.className+=" display";
> 
>         errors = true;
>     } } evt.preventDefault(); if(errors ===false){
>     document.getElementById("contactus").submit(); } };
  • 写回答

1条回答 默认 最新

  • dongteng2534 2015-04-13 22:51
    关注

    You need to set all the data you need in an object, and send it as a JSON string in an AJAX request.

      document.getElementById('send').onclick = function (evt) {
    
            var errors = false; //Gets all the inputs from contact form var
            myNodeList = document.querySelectorAll('input, textarea, select');
            var data = {};
            //Declar the vars //var i, val; // empty Array
    
            //Start of loop  
            for (i = 0; i < myNodeList.length; i++) {
                // Get element
                val = myNodeList[i].value;
                data[myNodeList[i].id] = val;
                //Get pattern attribute of regEx
                regEx = new RegExp(val.getAttribute("pattern"));
    
                //Get Error message
                err = document.getElementById(val.id + "-error")
    
                //By default, set the class to error, which hides the error message
                err.className = "error";
    
                //Test value "val" again the regEx
                if (!regEx.test(val.value)) {
                    //input fails and does not pass regEx test, set .display class
                    err.className += " display";
    
                    errors = true;
                }
            }
    
            evt.preventDefault();
            if (errors === false) {
                var req = new XMLHttpRequest();
    
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.open('POST', 'http://wirehopper.net/ajax-submit.php');
                req.onload = function () {
                    if(req.status == 200)
                        alert(req.response);
                }
                //TODO: implement error handling
                req.send(JSON.stringify(data));
    
            };
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页