簡體   English   中英

無法同時使用ajax jquery進行POST和JSON

[英]Unable to simultaneously POST and JSON with ajax jquery

我懷疑這可能是服務器問題,但是由於我沒有訪問服務器的權限,因此我希望其他人可以解決此問題,或者可以向我解釋導致問題的確切原因。

問題 ....

使用JQuery AJAX,我無法同時將數據發布到php文件和從php文件接收json編碼的數據。 如果包含json dataType,則無法將數據從表單發布到php文件。 如果我沒有指定json數據類型(即注釋掉),那么我可以將數據發布到php文件中,但是不能接收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);

?>

編輯....一個解決方案

好的...所以我發現了一個可行的hack。 我沒有指定dataType:'json',即注釋該行和contenType行。 然后,我就可以發布數據了。 仍然讓php文件回顯json_encode($ response_array)。 然后將以下代碼放入成功函數中

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

這不像能夠在ajax調用中指定dataType:'json'那樣好。 如果有人有更好的解決方案或可以解釋為什么會出現此問題,請告訴我。

謝謝

根據我的說法,您沒有做錯任何事情...除了您要說明很多事情...

例如: dataType: "json",

足以使ajax調用正常工作。...無需

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

在您的代碼中,如果添加此行,由於某種原因(不是很確定實際原因),它將返回空數組。

但是現在我只說明

dataType: "json",

它就像一個符咒一樣工作,在那里我得到了對象,而我不需要解析它。

編輯:

我嘗試的是followring ...只需將輸入名稱從name更改為fname,效果就很好

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM