需要通过json格式的javascript将数据发送到服务器

时间:2015-04-13 22:34:06

标签: javascript php ajax json

我无法将表单中的数据发布到服务器,但必须采用json格式并使用ajax。我如何使用javascript& amp; 无法使用Jquery 这里是我的问题......

还提前致谢!

  • 我如何转换它并将其发送到服务器并处理HTTP 200成功并使用ajax?

  • 返回JSON 对象的状态编码如下:{“status”:“---”},其中“---”是“成功”或“错误”。

  • 如果响应状态成功,则应该收到感谢信息 显示。
  • 如果响应状态为错误,则页面应显示常规 警告,例如“请求无法完成”。

    HTML

                    联络我                 

    <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 个答案:

答案 0 :(得分:1)

您需要在对象中设置所需的所有数据,并将其作为JSON字符串发送到AJAX请求中。

  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));

        };
    }