简体   繁体   English

getJSON在函数内导致无限循环

[英]getJSON inside a function causing an infinite loop

I'm working on a Codeigniter application and in a page I'm using jQuery to make an Ajax call to a function inside a controller. 我正在研究Codeigniter应用程序,在一个页面中,我使用jQuery对控制器内的函数进行Ajax调用。 I pass to this function some values taken from the page; 我将从页面中获取的一些值传递给此函数; the function make some calculations and then I have to display the result. 该函数进行一些计算,然后我必须显示结果。 All of this withouth refreshing the page. 所有这一切都没有刷新页面。

The ajax code is this: ajax代码是这样的:

$.getJSON("photos/change_product", {product_id: product_type, ajax: 'true'}, function(data) {
        var options = [];
        for (var i = 0; i < data.length; i++) 
    {
        options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
    }
    $("select#options").html(options.join(''));
    })
};

When I trigger it from a click event on some html element it works just fine. 当我从一些html元素上的click事件触发它时,它工作得很好。 The problem is that I also need it to run when I load the page the first time. 问题是我第一次加载页面时也需要它运行。 So I thought I could move that code into a function and then call it wherever I needed it. 所以我认为我可以将该代码移动到一个函数中,然后在我需要的地方调用它。 So, I created a changeProduct function with the code above and then called it like this: 所以,我用上面的代码创建了一个changeProduct函数,然后像这样调用它:

$(document).ready(function() {

function changeProduct(product_type) {

    $.getJSON("photos/change_product", {product_id: product_type, ajax: 'true'}, function(data) {
        var options = [];
        for (var i = 0; i < data.length; i++) 
    {
        options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
    }
    $("select#options").html(options.join(''));
    })
};

var selected_product = $("ul#products li:first-child a");
changeProduct(selected_product);

And this is causing an infinite loop of page refreshing. 这导致页面刷新无限循环。 How can I avoid this? 我怎么能避免这个? Shall I create counters and conditionals or is there some better way? 我应该创建计数器和条件还是有更好的方法?

SOLVED: the problem is in the selected_product variable. 已解决:问题出在selected_product变量中。 It should be something like this: 它应该是这样的:

var selected_product = $("ul#products li:first-child a").val();

Is it because 'selected_product' is a jquery object? 是因为'selected_product'是一个jquery对象吗? Do you want to do something like $("ul#products li:first-child a").text() instead to get it's value? 你想做一些像$(“ul#products li:first-child a”)。text()来取得它的价值吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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