getJSON无法使用输入按钮

时间:2010-11-20 20:09:50

标签: jquery jquery-selectors

如果我有a href getJSON正常工作正常(获取警报消息框)但在哪里我使用input button然后它不起作用(没有警报消息),下面是我的示例使用a hrefinput button,我打开萤火虫,我没有看到响应中的任何数据。

工作

<a href="'http://host/Myservice.svc/GetCustomerBy?GetCustomerBy?GetCustomerBy=?">GetCustomerBy</a>


 $(function () {
            $('a').click(function () {
                $.getJSON(this.href, { id: '2' }, function (customer) {
                    alert(customer.Name);
                    alert(customer.Address);
                });
                return false;
            });
        });

无法正常工作

    <input type="button" id="driver" value="Load Data" />

  $("#driver").click(function (event) {

        $.getJSON('http://host/Myservice.svc/GetCustomerBy?GetCustomerBy=?', { id: '2' }, function (customer) {

            alert(customer.Address);
            alert(customer.Name);
        });
    });

2 个答案:

答案 0 :(得分:2)

试试这个:

$(function() {
    $('#driver').click(function() {
        $.getJSON('http://host/Myservice.svc/GetCustomerBy?GetCustomerBy=?', { id: '2' }, function (customer) {
            alert(customer.Address);
            alert(customer.Name);
        });
    });
});

请注意,调用包含在$(document).ready中,并且您不需要return false。也不需要对匿名回调使用event参数。

同时比较您的href地址与您在按钮中使用的地址不同。在href中你有:

http://host/Myservice.svc/GetCustomerBy?GetCustomerBy?GetCustomerBy=?

而在按钮中你有:

http://host/Myservice.svc/GetCustomerBy?GetCustomerBy=?

这是不一样的。因此,请确保使用正确的地址,无论该地址是什么。在这种情况下,FireBug会帮助你。

答案 1 :(得分:0)

您的网址看起来不对 - 太多了?似乎重复了GetCustomerBy。不应该是:

<input type="button" id="driver" value="Load Data" />

$("#driver").click(function (event) {

    $.getJSON('http://host/Myservice.svc/GetCustomerBy', { id: '2' }, function (customer) {

        alert(customer.Address);
        alert(customer.Name);
    });
});

这会导致网址看起来像http://host/Myservice.svc/GetCustomerBy?id=2