使用serialize()解析JSON请求失败;

时间:2013-07-18 07:50:59

标签: jquery html ajax json

以下代码,

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>



    <script type="text/javascript">
    /*<![CDATA[*/

    $(document).ready(function () {

        var value = $('#button input').val();
        var name = $('#button input').attr('name');

        $('#button input').remove();
        $('#button').html('<a href="#" class="cssSubmitButton" rel=' + name + '>' + value + '</a>');

        //global vars
        var form = $("#customForm");
        var name = $("#name");
        var nameInfo = $("#nameInfo");
        var email = $("#email");

        var emailInfo = $("#emailInfo");


        //On blur
        name.blur(validateName);
        email.blur(validateEmail);

        //On key press
        name.keyup(validateName);
        email.keyup(validateEmail);
        //On Submitting
        $('#button a').on('click', function () {                    

            var link = $(this);
            if(validateName() & validateEmail())
            {
                var link = $(this);
                var str = $("form").serialize();

                jQuery.ajax({
                    url : 'load.php',
                    data: str,  
                    type: 'GET',
                    cache: 'false',
                    dataType: "json",
                    beforeSend: function () {
                        link.addClass('loading');                   
                    },

                    success: function(data) {
                        link.removeClass('loading');
                        $('#button').css('display','none');     
                        $('#success').css('display','block');

                    },
                    error:function(x,e){
                        if(x.status==0)
                        {
                            alert('You are offline!!\n Please Check Your Network.');
                        }
                        else if(x.status==404)
                        {
                            alert('Requested URL not found.');
                        }
                        else if(x.status==500)
                        {
                            alert('Internel Server Error.');
                        }
                        else if(e=='parsererror')
                        {
                            alert('Error.\nParsing JSON Request failed.');
                        }
                        else if(e=='timeout')
                        {
                            alert('Request Time out.');
                        }
                        else 
                        {
                            alert('Unknow Error.\n'+x.responseText);
                        }
                    }       
                });

                return true
            }
            else
            {
                return false;
            }
        });


        //validation functions
        function validateEmail(){
            //testing regular expression
            var a = $("#email").val();
            var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
            //if it's valid email
            if(filter.test(a)){
                email.removeClass("error");
                emailInfo.text("Valid E-mail please, you will need it to log in!");
                emailInfo.removeClass("error");
                return true;
            }
            //if it's NOT valid
            else{
                email.addClass("error");
                emailInfo.text("Stop cowboy! Type a valid e-mail please :P");
                emailInfo.addClass("error");
                return false;
            }
        }
        function validateName(){
            //if it's NOT valid
            if(name.val().length < 4){
                name.addClass("error");
                nameInfo.text("We want names with more than 3 letters!");
                nameInfo.addClass("error");
                return false;
            }
            //if it's valid
            else{
                name.removeClass("error");
                nameInfo.text("What's your name?");
                nameInfo.removeClass("error");
                return true;
            }
        }
    });

    /*]]>*/
    </script>

我的HTML论坛:

<form method="post" action="" id="subscribeForm" name="subscribeForm">
    <fieldset>
        <label>Name: </label><input type="text" class="effect" name="name" id="name"  autocomplete="off" >
        <span id="nameInfo">What's your name?</span>
    </fieldset>

    <fieldset>
        <label>Email: </label><input type="text" class="effect" name="email" id="email"  autocomplete="off" >
        <span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
    </fieldset>

    <div id="button">
        <input type="submit" value="Subscribe" name="subscribeForm"/>
    </div>
    <div id="success">
        <strong>Data Saved Successfully.</strong>
    </div>
</form>

它给我错误:解析JSON请求失败。

这是我在萤火虫中得到的,

load.php?name=asdf&email=ASDF%40gmail.com

这是我的PHP代码

<?php
sleep(3);
echo parse_str($_POST['str']);
?>

3 个答案:

答案 0 :(得分:1)

只需使用.serializeArray()方法:

var str = $("form").serializeArray();

答案 1 :(得分:0)

试试这个:

jQuery.ajax({
            url : 'load.php',
            data: str,  
            type: 'POST',
            cache: 'false',
            dataType: "json",
            beforeSend: function () {
                link.addClass('loading');                   
            },

            success: function(data) {
                link.removeClass('loading');
                $('#button').css('display','none');     
                $('#success').css('display','block');
                var json = JSON.parse(data);                    
                alert(json.response); // Here you get the value

            },
            error:function(x,e){
                if(x.status==0)
                {
                    alert('You are offline!!\n Please Check Your Network.');
                }
                else if(x.status==404)
                {
                    alert('Requested URL not found.');
                }
                else if(x.status==500)
                {
                    alert('Internel Server Error.');
                }
                else if(e=='parsererror')
                {
                    alert('Error.\nParsing JSON Request failed.');
                }
                else if(e=='timeout')
                {
                    alert('Request Time out.');
                }
                else 
                {
                    alert('Unknow Error.\n'+x.responseText);
                }
            }  

根据jQuery Documentation dataType 是您希望从服务器返回的数据类型,而不是发送给它的数据。使用POST并直接发送表单序列化就足够了,因为序列化是HTTP请求数据的实际格式。它将直接转换为$ _POST值。

在服务器端:

<?php
    sleep(3);
    $str = $_POST['str'];

    // Do whatever processing you need here with $str...

    // Set an array containing the response (it will be translated to JSON later)
    // You can use any kind of array, then you'll access the values like this in Javascript:
    // var resp = JSON.parse(data);
    // alert( resp.response );
    // or: alert( resp.whateverKeyYouUsed );
    $ret = array( "response" => "Some response message." );

    // Because the script is expecting a JSON response, encode the array and print it
    // The response would be something like {"response":"Some response message."} which is JSON
    echo json_encode($ret);
?>

答案 2 :(得分:0)

<强>建议:

  1. 将“data: str”更改为data: {str:str}
  2. parse_str($_POST['str']);更改为parse_str($_GET['str']); 因为,您在 ajax 中使用了“ GET ”方法。
  3. parse_str converts all the query string in php var。之后, parse_str($_GET['str'])您可以按echo $name;
  4. 显示用户名
  5. 您正在使用 json ajax ,因此您必须返回正确的json 来自url的数据,请在load.php
  6. 中使用以下示例

    然后,您可以通过 data.name

    AJAX 响应中获取名称
    <?php
    parse_str($_GET['str']);
    echo json_encode(array(
        'name' => $name
    ));
    ?>
    
    //or
    
    <?php
    parse_str($_GET['str'], $response);
    echo json_encode($response);
    ?>