Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

html - JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

I have two select elements, A and B: when A's selected option changes, B's options must be updated accordingly. Each element in A implies many elements in B, it's a one-to-many relationship (A contains nations, B should contain cities located in the given nation).

The function do_ajax should run the asynchronous request:

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: mydata,
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}

In order to update B's options I've added a function call in A's onChange event. Here is the function that runs when onChange event (of A) is triggered:

function my_onchange(e) // "e" is element "A"
{
    var sel_B = ... ; // get select element "B"

    // I skipped some code here
    // ...

    var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
    };
    do_ajax(city_sel, data, 'ajax_handler.php');
}

}

I've read in JQuery docs that data can be an array (key value pairs). I get the error if I put:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

Instead, I don't get that error if my data is a string:

var data = 'mode=filter_city&id_A=' + e[e.selectedIndex];

But I need the "array version" of the variable, in my server-side php code.

The Uncaught TypeError: Illegal invocation is located in the "jquery-1.7.2.min.js" file, which is all compressed, so I couldn't figure out what part of code raised the error.

Is there any setting I can change in my code so that it accepts data as an associative array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to the talk with Sarfraz we could figure out the solution.

The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities table and filter correct entries).

So, instead of:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

it should be:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex].value
};

Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...