0

I have a function that uses AJAX to get a list of items from a php script and can pass a filter. The user can set the filter by selecting from a drop down box on the page.

The problem i'm having is I am calling the function during page load to fill the form with default data and the function is just quitting silently when I try to read the filter text from the drop down box. It works fine after page load, but not during. However the function works fine if I put an alert("test") before it tries to read from the drop down so i'm assuming the drop down just hasnt finished loading properly when the function is called. How can I test to see if its safe to read so I can provide my own default value if it isnt safe?

Code Snippit:

var ProdCat = document.getElementById("prod_cat2");             
var Filter = "All Products";

Filter = ProdCat.options[ProdCat.selectedIndex].text;

alert("test");

xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();

So the above code is in a function called onLoad and the alert doesnt trigger at all. But if I comment out the Filter = ProdCat.(etc) line then the alert DOES trigger. Alert ALWAYS triggers even with that line AFTER page load. Looking for a solution to keep the one function both during load and after, thanks!

4

2 回答 2

2

听起来该脚本位于 HTML 文件中选择框的标记之上。ProdCat如果是这样,最简单的方法是简单地将script包含它的标签向下移动,使其位于选择框的标记下方。选择框在其标记被解析之前不会存在,但一旦存在就会立即存在。

我如何测试它是否可以安全阅读,以便在不安全的情况下提供我自己的默认值?

如果您不想重新定位脚本(或者在其他没有意义的情况下遇到这种情况),您可以测试您是否获得了该元素:

if (ProdCat) {
    Filter = ProdCat.options[ProdCat.selectedIndex].text;
}

如果你愿意,你甚至可以让它重试:

var ProdCat;
var Filter = "All Products";

function startAjax() {
    ProdCat = document.getElementById("prod_cat2");
    if (ProdCat) {
        Filter = ProdCat.options[ProdCat.selectedIndex].text;
        xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
        xr2.send();
    else {
        setTimeout(startAjax, 100); // 1/10th of a second later, try again
    }
}

startAjax();

更新:在评论中,您说:

错误是:ProdCat.options[ProdCat.selectedIndex] is undefined

好的,所以你有元素,但没有选择(还)。所以测试将是:

if (ProdCat &&                              // We have the select
    ProdCat.selectedIndex >= 0 &&           // and it has a selected value
    ProdCat.options[ProdCat.selectedIndex]  // (Paranoia) and that option exists
    ) {
    Filter = ProdCat.options[ProdCat.selectedIndex].text;
}
于 2013-07-30T15:15:15.303 回答
1

检查是否可以找到该元素。如果不是,则使用默认过滤器“所有产品”。

var ProdCat = document.getElementById("prod_cat2");             
var Filter = "All Products";

if (ProdCat)
{
  Filter = ProdCat.options[ProdCat.selectedIndex].text;
}

alert("test");

xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();
于 2013-07-30T15:13:44.440 回答