0

下面的代码,

<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']);
?>
4

3 回答 3

1

只需使用.serializeArray()方法:

var str = $("form").serializeArray();
于 2013-07-18T07:53:45.190 回答
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 DocumentationdataType是您期望从服务器返回的那种数据而不是发送给它的数据。使用 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);
?>
于 2013-07-18T08:15:09.927 回答
0

建议:

  1. 将“ ”更改data: strdata: {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. 您正在将jsonajax一起使用,因此您必须从 url返回正确的 json 数据,在 load.php 中使用以下示例

然后,您可以通过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);
?>
于 2013-07-18T09:23:12.063 回答