php - 防止多次执行 JavaScript 函数

标签 php javascript jquery ajax execution

我正在使用 JavaScript、jQuery 和 PHP。如何限制 JavaScript 函数执行一次?

我的 MainJQuery 文件有 Ajax。 display.php 执行一会:

....

$.ajax({
    type:'POST',
    url: 'display.php',
    data:'id='+id  ,
    success: function(data){
        $("#response").html(data);

        //Here Get_list should be execute only once.
        get_list('get');

        // Display should execute as usual
        display();
    }//success
}); //Ajax

.......

get.Php 文件向 JavaScript 写入一个值:

<?php
    print "<script language='javascript'>";
    print " g_cost[g_cost.length]=new Array('STA-VES','East',4500);";
    print " g_cost[g_cost.length]=new Array('STA-CRF','West',5400);";
    print "</script>";
?>

我的 JavaScript 函数具有来自 PHP 的以下值:

function get_list('get'){
    for(var i=0;i<g_cost.length;i++)
        var temp = g_cost[i];

    var Name = temp[0];
    var direction = temp[1];
    var cost = temp[2];

    ..
    some code
    ...
}

function display(){
    for(var i=0;i<g_cost.length;i++)
        alert(g_cost.length);
    var temp = g_cost[i];
    alert(temp[0]);
    alert(temp[1]);
    alert(temp[2]);
}

是否可以限制在 jQuery Ajax 成功部分执行 JavaScript 函数?

最佳答案

在 jQuery 中,您可以使用 .one() 函数来绑定(bind)只执行一次的方法。例如,

$("#someAnchorId").one("click", function(){
    //Ajax method here 
});

参见 jQuery one help topic .

关于php - 防止多次执行 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/432721/

相关文章:

php - ajax 查询返回的数组看起来不错,但它的器官没有正确显示

PhpStorm:无法评估表达式 '$_SERVER[' SERVER_PORT']'

php - Paypal 立即购买按钮重定向

Javascript 明显的疯狂

javascript - jQuery - 变量范围问题

javascript - 滚动时如何将类 "active"添加到下一个 <div>

jquery - href点击事件到。按钮点击事件。使困惑?

php - 在一对多关系中至少获取一次包含所有 child 的 parent 列表

javascript - 如何从无限循环的 Javascript 函数向 MySQL 传递值?

javascript - Angular 6-在同一组件的变量更改时动态更改 *ngFor 元素的 css 属性