根据Ajax返回的数据提交表单

时间:2016-03-18 09:43:09

标签: javascript jquery ajax

所以我有一个带有ajax脚本的表单.Ajax调用一个从API返回数据的php文件,如果从php文件返回的代码不是所需的代码,我想中止提交。因为它是form从ajax获取数据,无论返回什么数据都仍然提交。我错过了什么?



<form id="login" class="" action="http://someurl/login" method="post">
    <div class=""><input id="email" class="" name="email" type="text" placeholder="Email" /></div>
    <div class=""><input id="password" class="" name="password" type="password" placeholder="Password" /></div>
    <div class=""><button class="btn btn-primary custom-button" id="log" onclick="ajaxtest();" name="submit" type="submit">Login</button></div>
</form>
&#13;
&#13;
&#13;

function ajaxtest() {

    var email = $("#email").val();
    var password = $("#password").val();
    var dataString = 'email=' + email + '&password=' + password;
    if (email == '' || password == '') {
        alert("Please Fill All Fields");
    } else {
        // AJAX Code To Submit Form.
        $.ajax({
            type: "POST",
            url: "login.php",
            async: false,
            data: dataString,
            cache: false,
            success: function(result) {


                if (result.content == 'some number') {

                    $('#login').submit();
                } else {

                    throw new Error(result.content);
                }
            },

        });
    }
}

在httpfox中,我可以看到ajax返回的POST数据,很好。

修改

<?php
$loginUrl="http://someapi/login?token=blah";

    $data = array("email" => $_POST['email'], "password" => sha1($_POST['password']));



$json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json))
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$content =  curl_exec($ch);

$code= json_decode($content,true);
$code=$code['code'];

echo $code;

?>

4 个答案:

答案 0 :(得分:1)

您需要使用e.preventDefault();

来阻止默认点击触发器
function ajaxtest(e) {
e.preventDefault();
    var email = $("#email").val();
    var password = $("#password").val();
    var dataString = 'email=' + email + '&password=' + password;
    if (email == '' || password == '') {
        alert("Please Fill All Fields");
    } else {
        // AJAX Code To Submit Form.
        $.ajax({
            type: "POST",
            url: "login.php",
            async: false,
            data: dataString,
            cache: false,
            success: function(result) {


                if (result.content == 'some number') {

                    $('#login').submit();
                } else {

                    throw new Error(result.content);
                }
            },

        });
    }
}

答案 1 :(得分:1)

据我了解你的问题,

数据将作为JSON的字符串表示形式返回,并且您不会将其转换回JavaScript对象。

你的ajax电话中的

dataType:'json'或者你可以使用JSON.parse(result); 在你的成功功能中。

答案 2 :(得分:1)

因为你没有阻止这个形式的提交。您应该做的是为“提交”注册回调。表单元素本身上的事件

first remove ajaxtest() as inline script

然后创建一个新的表单提交功能

function myLoginSubmit(){
     if(  $('#login').data('myLoginValidated')){
         // this should be after you ajax request 
         ///formElement.submit();
         return true ;
     }else(){
        // only prevents submition  if not validated
        ajaxtest(e);
        return false;
     }
}

现在挂钩表单子目录

$("#login").submit(function(){
     return myLoginSubmit()
});

最后改变

if (result.content == 'some number') {

                $('#login').submit();
            } else {

                throw new Error(result.content);
            }

if (result.content == 'some number') {
                // now you made sure its what you want, then submit the form
                // the form wont be prevented because we set third parameter to True
                 //myLoginSubmit( null ,  $('#login') , true )
                   $('#login').data('myLoginValidated' , true);
                  return  $('#login').submit();
            } else {

                throw new Error(result.content);
            }

答案 3 :(得分:0)

出于某种原因,上述答案都没有对我有用,这就是我最终解决的问题

$customer_order_postcode ='S5 9PO';
//strip anything after the space in a postcode
$customer_postcode = substr($customer_order_postcode, 0, strrpos($customer_order_postcode, ' '));

$islands_postcodes = 'HS1,HS2,HS3,HS4,HS5,HS6,HS7,HS8,HS9,IV41,IV42,IV43,IV44,IV45,IV46,IV48,V49,IV51,IV55,IV56,KA27,KA28,KW15,KW16,KW17,PA20,PA41,PA42,PA43,PA44,PA45,PA46,PA47,PA48,PA49,PA60,PA61,PA62,PA63,PA64,PA65,PA66,PA67,PA68,PA69,PA70,PA71,PA72,PA73,PA74,PA75,PA76,PA77,PA78,PH41,PH42,PH43,PF44,ZE1,ZE2,ZE3,IM,GY,JE';

$search_highlands = strpos($islands_postcodes, $customer_postcode);

if($search_highlands==true) $country = 'H'.$customer_postcode;

print($country);