简体   繁体   English

无法同时使用ajax jquery进行POST和JSON

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

I suspect that this might be a server issue, but since I do not have access to our server, I was hoping maybe someone else had a fix or could explain to me exactly what is causing the problem. 我怀疑这可能是服务器问题,但是由于我没有访问服务器的权限,因此我希望其他人可以解决此问题,或者可以向我解释导致问题的确切原因。

The problem .... 问题 ....

Using JQuery AJAX I am unable to simultaneously POST data to a php file and receive json encoded data from the php file. 使用JQuery AJAX,我无法同时将数据发布到php文件和从php文件接收json编码的数据。 If the json dataType is included I am unable to POST data from the form to the php file. 如果包含json dataType,则无法将数据从表单发布到php文件。 If I do not specify the json dataType (ie comment it out) then I can POST data to the php file but cannot receive the json encoded data. 如果我没有指定json数据类型(即注释掉),那么我可以将数据发布到php文件中,但是不能接收json编码的数据。

I've tried this with my own js/php code and for source code that I downloaded, in order to compare results in case it was just a mistake in my coding. 我已经用自己的js / php代码和我下载的源代码尝试过此操作,以便比较结果以防万一这只是我的编码中的错误。 Both are 'submit forms' and both exhibit the problems outlined above. 两者都是“提交表格”,并且都表现出上述问题。 In case its relevant, I include the downloaded source code below. 如果相关,请在下面提供下载的源代码。 My js/php code uses similar ajax requests. 我的js / php代码使用类似的ajax请求。

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

the PHP: 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);

?>

EDIT....One Solution 编辑....一个解决方案

Ok...so I found a hack that works. 好的...所以我发现了一个可行的hack。 I don't specify the dataType:'json', ie comment that line and the contenType line out. 我没有指定dataType:'json',即注释该行和contenType行。 Then I'm able to POST the data. 然后,我就可以发布数据了。 Still have the php file echo the json_encode($response_array). 仍然让php文件回显json_encode($ response_array)。 Then put the following code in the success function 然后将以下代码放入成功函数中

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

This is not as nice as being able to specify the dataType:'json' in the ajax call. 这不像能够在ajax调用中指定dataType:'json'那样好。 If anyone has a better solution or can explain why this problem is occurring, let me know. 如果有人有更好的解决方案或可以解释为什么会出现此问题,请告诉我。

Thanks 谢谢

According to me you are doing nothing wrong... except you are specifying to many things... 根据我的说法,您没有做错任何事情...除了您要说明很多事情...

For eg: dataType: "json", 例如: dataType: "json",

is sufficient for ajax call to work.... there is no need for 足以使ajax调用正常工作。...无需

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 我尝试的是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