【问题标题】:Unable to simultaneously POST and JSON with ajax jquery无法使用 ajax jquery 同时 POST 和 JSON
【发布时间】:2012-05-09 18:15:06
【问题描述】:

我怀疑这可能是服务器问题,但由于我无法访问我们的服务器,我希望也许其他人已经修复或可以向我解释导致问题的确切原因。

问题....

使用 JQuery AJAX 我无法同时将数据发布到 php 文件并从 php 文件接收 json 编码数据。如果包含 json dataType,我无法将表单中的数据发布到 php 文件。如果我没有指定 json 数据类型(即注释掉),那么我可以将数据 POST 到 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);

?>

编辑....一个解决方案

好的...所以我找到了一个可行的方法。我没有指定 dataType:'json',即注释该行和 contenType 行。然后我就可以发布数据了。仍然有 php 文件回显 json_encode($response_array)。然后将如下代码放入成功函数中

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

这不如在 ajax 调用中指定 dataType:'json' 好。如果有人有更好的解决方案或可以解释为什么会出现此问题,请告诉我。

谢谢

【问题讨论】:

    标签: php javascript jquery ajax


    【解决方案1】:

    在我看来,你没有做错任何事情......除了你指定了很多事情......

    例如: dataType: "json",

    足以让 ajax 调用工作.... 不需要

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

    在您的代码中,如果您添加此行,它会出于某种原因返回空数组(不太确定实际原因)....

    但我只是指定的那一刻

    dataType: "json",

    它就像一个魅力,作为回报,我得到了我不需要解析的对象。

    编辑:

    我尝试的是如下...只需将输入名称从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>
    

    【讨论】:

    • 我只尝试了 dataType,但没有成功。看到here后,我包含了contentType,然后就可以提交ajax请求了。
    猜你喜欢
    • 1970-01-01
    • 2016-06-24
    • 2013-04-30
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    相关资源
    最近更新 更多