0

これはサーバーの問題であると思われますが、私はサーバーにアクセスできないため、他の誰かが修正を行っているか、問題の原因を正確に説明してくれることを望んでいました.

問題 ....

JQuery AJAXを使用すると、データをphpファイルに同時にPOSTすることと、phpファイルからjsonでエンコードされたデータを受け取ることができません。json dataType が含まれている場合、フォームから php ファイルにデータを POST できません。json dataType を指定しない (つまり、コメントアウトする) と、データを php ファイルに POST できますが、json でエンコードされたデータを受け取ることができません。

私は自分の js/php コードとダウンロードしたソース コードでこれを試しました。これは、コーディングの間違いである場合に備えて結果を比較するためです。どちらも「送信フォーム」であり、上記で概説した問題を示しています。関連する場合は、ダウンロードしたソース コードを以下に含めます。私の js/php コードは、同様の ajax リクエストを使用しています。

JavaScript:

<script type="text/javascript">

        $(document).ready(function(){

            $("#myForm").submit(function(){
                dataString = $("#myForm").serialize();
                $.ajax({
                    type: "POST",
                    url: "postForm_ajax.php",
                    data: $("#myForm").serialize(),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function(msg){
                        $("#formResponse").removeClass('error');
                        $("#formResponse").addClass(msg.status);
                        $("#formResponse").addClass(msg.status);

                    },
                    error: function(){
                        $("#formResponse").removeClass('success');
                        $("#formResponse").addClass('error');
                        $("#formResponse").html("There was an error submitting the form. Please try again.");
                    }
                });

                //make sure the form doens't post
                return false;


            });


        });
    </script>

PHP:

<?php
//function to validate the email address
//returns false if email is invalid
function checkEmail($email){

if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
//if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
    return FALSE;
}

list($Username, $Domain) = explode("@",$email);

if(@getmxrr($Domain, $MXHost)){
    return TRUE;

} else {
    if(@fsockopen($Domain, 25, $errno, $errstr, 30)){
        return TRUE; 
    } else {

        return FALSE; 
    }
}
}   



//response array with status code and message
$response_array = array();

//validate the post form
//$name = $_POST['name'];
//check the name field
if(empty($_POST['name'])){

//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';

//check the email field
} elseif(!checkEmail($_POST['email'])) {

//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';

//check the message field
} elseif(empty($_POST['message'])) {

//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';


//form validated. send email
} else {

//send the email
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);

//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';

}


echo json_encode($response_array);

?>

編集....1つの解決策

わかりました...それで、機能するハックを見つけました。dataType:'json' は指定しません。つまり、その行と contentType 行をコメントアウトします。その後、データを POST できます。まだ php ファイルに json_encode($response_array) をエコーさせます。次に、次のコードを成功関数に入れます

var obj = jQuery.parseJSON(msg);
$("#formResponse").addClass(obj.status);
$("#formResponse").html(obj.message);

これは、ajax 呼び出しで dataType:'json' を指定できるほど便利ではありません。誰かがより良い解決策を持っている場合、またはこの問題が発生している理由を説明できる場合は、お知らせください。

ありがとう

4

1 に答える 1

0

According to me you are doing nothing wrong... except you are specifying to many things...

For eg: dataType: "json",

is sufficient for ajax call to work.... there is no need for

contentType: "application/json; charset=utf-8",

in your code, if you add this line it returns the empty array in return for some reason (not very sure about the actual reason)....

But moment I specify just

dataType: "json",

it works like a charm where in return I get the object, which I need not parse.

edit:

What I tried is as followring... just change the input name to fname from name and it worked very well

<form id="myForm" name="myForm" method="POST"
    action="postform_ajax.php">
    name: <input type="text" name="fname" /> <br /> email: <input
        type="text" name="email" /> <br /> message: <input type="message"
        name="message" /> <br /> <input type="submit" />
    <div id="formResponse"></div>
</form>
<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {

        $("#myForm").submit(function() {
            dataString = $("#myForm").serialize();
            $.ajax({
                type : "POST",
                url : "postForm_ajax.php",
                data : $("#myForm").serialize(),
                dataType : "json",
                success : function(msg) {
                    $("#formResponse").removeClass('error');
                    $("#formResponse").addClass(msg.status);
                    $("#formResponse").html(msg.status);
                },
                error : function() {
                    console.log('err', msg);
                    $("#formResponse").removeClass('success');
                    $("#formResponse").addClass('error');
                    $("#formResponse").html("There was an error submitting the form. Please try again.");
                }
            });

            //make sure the form doens't post
            return false;

        });

    });
</script>
于 2012-05-09T18:54:49.043 に答える