-2

asp.net ページに Jquery AJAX を実装しようとしています。$.post または $.ajax をスクリプトのどこに配置すればよいですか。

4

1 に答える 1

2

You don't necessarily need to place the $.post and $.ajax calls in a document.ready callback. You need to do that only if you want to pass as parameter some value that is part of the DOM. But you could perfectly fine trigger an AJAX request before your DOM is loaded if all values you are sending are not DOM dependent. The only constraint is that the script need to be placed after the jquery.js script script inclusion. For example you could place the following script in the <head> section of your page without any document.ready:

<head>
    ...
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $.post('/some_script.cgi', { foo: 'bar' }, function(result) {
            alert('success');
        });
    </script>
</head>

But if you wanted to pass some value that is part of your DOM then you need to wrap in a document.ready:

<head>
    ...
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            // Here you are accessing the DOM to get the value of the 
            // #some_element_id so you need to place your script in a 
            // document.ready
            var value = $('#some_element_id').html();
            $.post('/some_script.cgi', { foo: value }, function(result) {
                alert('success');
            });
        });
    </script>
</head>

So as you can see it will all depend on your specific scenario but the $.post and $.ajax methods do not require at all being placed in a document.ready callback.

于 2013-09-15T16:38:38.437 に答える