簡體   English   中英

為什么我的Ajax登錄表單無法正常工作?

[英]Why my ajax login form doesn't work correctly?

我使用AJAX創建一個登錄表單。 這是我的JQUERY代碼:

$("#logbtn").on("click" , function() {
  if (!$("div").hasClass("error"))
  {
    $.ajax
    ({
    type:'post',
    url:'http://localhost/mysite/wp-content/themes/facecar/admin/inc/proccesslogin.php',
    data:{
     username: $("#loguser").val(),
     password: $("#logpass").val()
    },
    success:function(response) {
      console.log(response);
      if (response == "yes")
      {
        alert("answer is yes ");
      } else {
        alert("answer is no !");
      }
    }
    });
  }
});

這是我的PHP代碼:

<?php
  if (strpos($_POST["username"] , "moria") >= 0)
    {
      echo "yes";
    } else {
      echo "false";
    }
?>

我將響應放在控制台中,它顯示我的php代碼並警告“答案為否!” 有什么問題?

我相信,您使用的是wordpress,而在wordpress中嘗試ajax的方式不是正確的方法。 在wordpress中,ajax網址是admin_url( 'admin-ajax.php' ) 您將從以下鏈接中得到一個想法: 在wordpress中從前面調用Ajax 希望您可以按照該鏈接進行其余操作。

讓您輕松理解...

寫在你的functions.php

/* include your js script */
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
function my_enqueue_scripts() {
    //Change the key and url with yours
    wp_register_script('my-js', get_stylesheet_directory_uri(). '/js/my-js.js', array( 'jquery' ) );
    wp_enqueue_script('my-js');

    //Localize script data to be used in my-js.js
    $scriptData = array();
    $scriptData['ajaxurl'] = admin_url( 'admin-ajax.php' );
    $scriptData['action'] = 'answerAction';

    wp_localize_script( 'my-js', 'my_js_data', $scriptData );

}
/* Add your server code */
add_action("wp_ajax_answerAction", "answerAction");
add_action("wp_ajax_nopriv_answerAction", "answerAction");
function answerAction(){
    if (strpos($_POST["username"] , "moria") >= 0)
    {
      echo "yes";
    } else {
      echo "false";
    }
    die();
}

現在,在my-js.js中添加您的js腳本

(function($){
    $(document).ready(function(){
        $('#logbtn').on('click',function(e){
            e.preventDefault();
            var data = {
                'action': my_js_data.action,
                'username': jQuery("#loguser").val(),
                'password': jQuery("#logpass").val()
            };
            if (!$("div").hasClass("error"))
            {
                jQuery.post( my_js_data.ajaxurl, data, function(response) {
                    console.log(response);
                    if (response == "yes")
                    {
                        alert("answer is yes ");
                    } else {
                        alert("answer is no !");
                    }
                });
            }
        });
    });
})(jQuery);

祝你好運。

暫無
暫無

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

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