jquery ajax 功能不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21796947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:41:50  来源:igfitidea点击:

jquery ajax function not working

jqueryhtmlajax

提问by Kiran Gopalakrishnan

my html goes like this ,

我的 html 是这样的,

<form name="postcontent" id="postcontent">
    <input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
    <textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>

The jquery code is as follows

jquery代码如下

$("#postcontent").submit(function(e) {
    $.ajax({
        type:"POST",
        url:"add_new_post.php",
        data:$("#postcontent").serialize(),
        beforeSend:function(){
            $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
        },success:function(response){   
            //alert(response);
            $("#return_update_msg").html(response); 
            $(".post_submitting").fadeOut(1000);                
        }
    });
});

When I click on the submit button , my ajax request is not working , it looks as if the control is being passed to the JQuery submit function , but the ajax request is not executing/working properly,what is wrong ?

当我单击提交按钮时,我的 ajax 请求不起作用,看起来好像控制权正在传递给 JQuery 提交函数,但是 ajax 请求没有执行/正常工作,有什么问题?

回答by java seeker

put the event handler function inside $(document).ready(function(){...}). it shall work now

将事件处理函数放在 $(document).ready(function(){...}) 中。它现在可以工作了

also add preventDefault() to restrict page refreshing

还添加 preventDefault() 以限制页面刷新

$(document).ready(function() {

            $("#postcontent").submit(function(e) {
                e.preventDefault();
                $.ajax({
                    type : "POST",
                    url : "add_new_post.php",
                    data : $("#postcontent").serialize(),
                    beforeSend : function() {
                          $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
                    },
                    success : function(response) {
                        alert(response);
                        $("#return_update_msg").html(response);
                        $(".post_submitting").fadeOut(1000);
                    }
                });
                e.preventDefault();
            });

        });

回答by Janak Prajapati

try this code

试试这个代码

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<Script>
$(document).ready(function(){

$("#postcontent").click(function(e) {

        $.ajax({type:"POST",url:"add_new_post.php",data:$("#postcontent").serialize(),beforeSend:function(){
            $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
        },success:function(response){   
                    //alert(response);
                    $("#return_update_msg").html(response); 
                    $(".post_submitting").fadeOut(1000);                
            }
        });
   });
});
   </script>

<form name="postcontent" id="postcontent">
              <input name="postsubmit" type="button" id="postsubmit" value="POST"/>
              <textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
 </form>

回答by Drixson Ose?a

you need to prevent the default behavior of your form when submitting

您需要在提交时防止表单的默认行为

by adding this:

通过添加这个:

$("#postcontent").on('submit' , function(e) {

  e.preventDefault();

  //then the rest of your code
}

回答by Ashwin Sinha

Try this

尝试这个

    $("#postcontent").submit(function() {
  return false;
};

$('#postsubmit').click(function(){

// your ajax request here
});

回答by Pravin Tukadiya

I think you have putted e.preventDefault(); before ajax call that's why its prevent calling of that function and your Ajax call will not call.

我想你已经把 e.preventDefault(); 在 ajax 调用之前,这就是为什么它会阻止调用该函数并且您的 Ajax 调用不会调用。

So try to remove that e.prevent Default() before Ajax call and add it to the after Ajax call.

因此,尝试在 Ajax 调用之前删除 e.prevent Default() 并将其添加到 Ajax 调用之后。

回答by Byron

For the sake of documentation. I spent two days working out an ajax problem and this afternoon when I started testing, my PHP ajax handler wasn't getting called....

为了文档。我花了两天时间解决了一个 ajax 问题,今天下午当我开始测试时,我的 PHP ajax 处理程序没有被调用......

Extraordinarily frustrating.

异常的令人沮丧。

The solution to my problem (which mighthelp others) is the priority of the add_action.

我的问题的解决方案(可能对其他人有帮助)是 add_action 的优先级。

add_action ('wp_ajax_(my handler), array('class_name', 'static_function'), 1);

add_action ('wp_ajax_(my handler), array('class_name', 'static_function'), 1);

recalling that the default priority = 10

回想一下默认优先级 = 10

I was getting a return code of zero and none of my code was being called.

我得到的返回码为零,并且没有调用我的任何代码。

...noting that this wasn't a WordPress problem, I probably misspoke on this question. My apologies.

...注意到这不是 WordPress 问题,我可能在这个问题上说错了。我很抱歉。

回答by Dev Nath

I am doing a code like this

我正在做这样的代码

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
    src="http://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script>
    $(document).ready(function () {

        $(".work-category a").click(function (e) {
            e.preventDefault();
            var id = $(this).attr('data-id');
            $.ajax({
                url: 'process.php',
                method: 'POST',
                data: {
                    clickCategoryID : id
                },
                dataType: 'JSON',
                success: function (data) {
                    $("#content-area").html(data.Content);
                    $(".container-area").animate({top: '100px'}, 1000);
                    $(".single-content").animate({opacity:1}, 1000);
                }
            });
        });

    });
</script>

But the code is not running and the console saya process.php not found though I have the code on it.

但是代码没有运行,虽然我有代码,但没有找到控制台 saya process.php。

回答by Zach Pedigo

I was having this issue and none of these answers were able to help me with the issue. For anyone else who happens to have the same problem, here is a possible solution that worked for me. Simply reformat the code to be the following:

我遇到了这个问题,但这些答案都无法帮助我解决这个问题。对于碰巧遇到同样问题的其他人,这里有一个可能对我有用的解决方案。只需将代码重新格式化为以下内容:

$("#postcontent").submit(function(e) {
  $.ajax({
    type:"POST",
    url:"add_new_post.php",
    data:$("#postcontent").serialize(),
    beforeSend:function(){
      $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
    },
    success (response) {   
      //alert(response);
      $("#return_update_msg").html(response); 
      $(".post_submitting").fadeOut(1000);                
    },
    error (data) {
      // handle the error
    }
  });
});

The difference in the code is that this code has an error handler. You can choose to handle the error however you wish but it is best practice to have the error handler in case of an exception. Also, the formatting of the success and error functions within the ajax function are different. This is the only format for success/error that would work for me. Hope it helps!

代码中的不同之处在于此代码具有错误处理程序。您可以根据自己的意愿选择处理错误,但最好的做法是在发生异常时使用错误处理程序。此外,ajax 函数中成功和错误函数的格式是不同的。这是唯一对我有用的成功/错误格式。希望能帮助到你!

回答by Suraj R Gholap

my html and js code

我的 html 和 js 代码

<script>
$(".editTest23").change(function () {

        var test_date = $(this).data('');id
        // alert(status_id);    

        $.ajax({
            type: "POST",
            url: "Doctor/getTestData",
            data: {
                test_data: test_date,
            },
            dataType: "text",
            success: function (data) {
                $('#prepend_here_test1').html(data);
            }
        });
        // you have missed this bracket
        return false;
    });
</script>

in php code

在 php 代码中

    foreach($patitent_data as $result){

        $result_html .="<tr class='test_record'>\
        <td><input type='text' name='test_name' value='$result->test_name' class='form-control'></td>\
        <td><textarea class='form-control' name='instruction'> $result->instruction </textarea>\
        </td>\
        <td><button class='close remove_test_record' aria-hidden='true'>&times;</button></td>\
     </tr>";
    }

    echo json_encode($result_html)

回答by lalaland

Give this a go:

试一试:

<form name="postcontent" id="postcontent">
    <input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
    <textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
<script>
    (function() {
        $("#postcontent").on('submit', function(e) {
            e.preventDefault();
        $.ajax({
            type:"POST",
            url:"add_new_post.php",
            data:$("#postcontent").serialize(),
            beforeSend:function(){
                $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
            },success:function(response){   
                //alert(response);
                $("#return_update_msg").html(response); 
                $(".post_submitting").fadeOut(1000);                
            }
        });
   });
})();
</script>