简体   繁体   中英

Two functions with .ajax() inside doesn't work together

In my JS file I have two functions:

function A () {
  ...
    $.ajax({
      type: "POST",
      url: "page.php",
      data: {<some data>}
    })
    .done(function( data ) {
      ...
    })
  ...
}

function B () {
  ...
    $.ajax({
      type: "POST",
      url: "page.php",
      data: {<some other data>}
    })
    .done(function( ) {
      ...
    })
}

Both these functions are called by onclick event of some anchors. So, somewhere in html file I have such code:

<a onclick="A()">Link to call A()</a>
<a onclick="B()">Link to call B()</a>

When I have only function A in my code everything works just fine. However, these functions both doesn't work when I have them in the code that you can see above. When I click on a link with onclick="A()" function A is not even called.

What is wrong? How can I fix it?

如果单击按钮时正在调用该函数,则删除$(document).ready(位。当用户单击按钮时,文档就绪状态已通过-这是在页面加载时运行的事件。

function A () {
  ...
    $.ajax({
      type: "POST",
      url: "page.php",
      data: {<some data>}
    })
    .done(function( data ) {
      ...
    });
  ...
}

function B () {
  ...
    $.ajax({
      type: "POST",
      url: "page.php",
      data: {<some other data>}
    })
    .done(function( ) {
      ...
    });
}

Write them as below. This way, your functions would be called on document ready and you can also call them on demand.

function A () {
    $.ajax({
        type: "POST",
        url: "page.php",
        data: {}
    })
    .done(function (data) {
    });
}

function B () {
    $.ajax({
        type: "POST",
        url: "page.php",
        data: {}
    })
    .done(function () {
    });
}

$(document).ready(A);
$(document).ready(B);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM