Javascript 为什么我的jQuery按钮处理程序没有被触发?

Javascript 为什么我的jQuery按钮处理程序没有被触发?,javascript,jquery,ajax,rest,Javascript,Jquery,Ajax,Rest,我使用此jQuery来响应被单击的按钮并调用REST方法: $(document).ready(function() { $("#btnGetData").click(function() { alert("The button was clicked."); var unitval = _unit; var begdateval = _beginDate; var enddateval = _endDate; var model = JS

我使用此jQuery来响应被单击的按钮并调用REST方法:

$(document).ready(function() {
    $("#btnGetData").click(function() {
    alert("The button was clicked.");

    var unitval = _unit; 
    var begdateval = _beginDate;
    var enddateval = _endDate; 

    var model = JSON.stringify({ unit: unitval, begdate: begdateval, enddate: enddateval });
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetQuadrantData", "LandingPage")',
        data: { unit: unitval, begdate: begdateval, enddate: enddateval},
        contentType: 'application/json',
        cache: false,
        success: function (returneddata) {
        },
        error: function () {
            alert('hey, boo-boo!');
        }
        });

    }); // button click
}); // ready
这不仅仅是因为REST方法没有被调用——这个处理程序显然根本没有启动,因为我没有看到任何警报(既没有“按钮被点击”,也没有“嘿,boo boo!”)

正在添加脚本-我可以单步执行它,并为变量(如“unitval”)分配适当的值

那么,为什么单击按钮(声明如下)会:

<button class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
更新 这是来自控制台的错误转储:

Failed to find a valid digest in the 'integrity' attribute for resource 'https://code.jquery.com/jquery-1.12.4.min.js' with computed SHA-256 integrity 'ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ='. The resource has been blocked.

Uncaught Error: Bootstrap's JavaScript requires jQuery

Failed to load resource: the server responded with a status of 404 (Not Found)

Uncaught Error: Bootstrap's JavaScript requires jQuery

Uncaught ReferenceError: $ is not defined

Failed to load resource: the server responded with a status of 404 (Not Found)
更新2 我添加jQuery;我在我的“头脑”部分有以下内容:

在执行此操作时,我确实会从javascript按钮单击事件处理程序中看到“ItWorks”警报,然后还会看到“hey,boo boo!”警报。永远不会到达“_unit=unit;”上的断点。我想这就是为什么我看到了“boo-boo”的信息,但我不知道为什么没有联系到它

更新5 Url.Action参数仍在转换/翻译错误;在Chrome开发工具中,它显示:

<script>
    $(document).ready(function () {
        $("#btnGetData").click(function () {
            $.ajax({
                type: 'GET',
                url: '/LandingPage/GetQuadrantData',
                console.log(url);
                data: {unit: unitval, begdate: begdateval, enddate: enddateval},
                contentType: 'text/plain',
                cache: false,
                xhrFields: {
                    withCredentials: false
                },
                success: function(returneddata) {
                    alert('Successful: ' + returneddata);
                },
                error: function() {
                    alert('hey, boo-boo!');
                }
            }); // ajax
        }); // button click
    }); // ready
</script>
…在CDT中被视为:

url: '/LandingPage/GetQuadrantData',
…我没有到达在下面最后一行设置的断点:

[System.Web.Http.Route("{unit}/{begdate}/{enddate}")]
[System.Web.Http.HttpGet]
public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
{
    _unit = unit;
更新6 在Ajax调用的中间,它跳过这条线:

console.log(url);
…但即使我将其剥离,使jQuery变成这样(向args/data添加一些随机数据值):

…我仍然会将“boo boo”消息写入控制台,并且我的控制器中的断点没有命中,可能是因为通过url.Action()方法生成了错误的url

更新7 如果我笨拙地/实验性地将ajax调用更改为此,将Url.Action和数据替换为原始Url:

$(document).ready(function () {
    $("#btnGetData").click(function () {
        $.ajax({
            type: 'GET',
            url: 'http://localhost:52194/api/ABUELOS/2016-08-21/2016-08-27',
            contentType: 'text/plain',
            cache: false,
            xhrFields: {
                withCredentials: false
            },
            success: function(returneddata) {
                console.log('Successful: ' + returneddata);
            },
            error: function() {
                console.log('hey, boo-boo!');
            }
        }); // ajax
    }); // button click
}); // ready
…我确实到达了控制器中的断点,但页面上的url没有更改,页面上的数据(html)也没有更新

顺便说一句,正如Nyedikeke建议的那样,我确实将jquery引用更改为:

<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
更新9 这是我在\App\u Start\WebApiConfig.cs中的注册方法:

public static void Register(HttpConfiguration config)
{
    config.Routes.Clear(); // added this 9/2/2016 at suggestion from http://www.codemag.com/article/1601031
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // I don't know if this is where this should go (from http://stackoverflow.com/questions/34626483/how-to-pass-datatable-via-frombody-to-web-api-post-method-c)
    config.Formatters.Add(new DataTableMediaTypeFormatter());
    config.Formatters.Add(new GenericProduceUsageListMediaTypeFormatter());
}

这里有什么问题吗?

如果您提交表单,请添加如下按钮类型:

<button type="submit" class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
提交
更新

从“更新2”的第一行更改以下内容:

<script src='https://code.jquery.com/jquery-1.12.4.min.js' integrity='sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=' crossorigin='anonymous'></script>

为此:

<script src='https://code.jquery.com/jquery-1.12.4.min.js'></script>

我们不需要在这里检查jquery文件的完整性,所以通过删除,您将能够运行jquery而不会出现任何错误。谢谢你的代码对我有用:

您确定正确导入了jQuery吗?如果没有,请在控制台中运行一些jquery函数,以确保它正常工作

<button class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
提交

试试看,它只是使用vanilla JS设置您的侦听器,然后用jQuery处理其余部分

在我做的测试页面上,我的警报很好

window.onload = function() {
    var btnGetData = document.getElementById('btnGetData')
    btnGetData.addEventListener("click", function() {
        alert("Twerking...");
        var unitval = _unit;
        var begdateval = _beginDate;
        var enddateval = _endDate;
        var model = JSON.stringify({
            unit: unitval,
            begdate: begdateval,
            enddate: enddateval
        });
        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetQuadrantData", "LandingPage")',
            data: {
                unit: unitval,
                begdate: begdateval,
                enddate: enddateval
            },
            contentType: 'application/json',
            cache: false,
            success: function(returneddata) {},
            error: function() {
                alert('hey, boo-boo!');
            }
        });
    }); // button click
}

伙计,有一个问题:你确定你正确地包含了jquery库吗

我试过这个,效果很好

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">   

    $(document).ready(function () {
        $("#btnGetData").click(function () {
            alert("The button was clicked.");

        }); // button click
    }); // ready
</script>

$(文档).ready(函数(){
$(“#btnGetData”)。单击(函数(){
警报(“按钮已单击”);
});//按钮点击
}); // 准备好的

为了成功访问按钮上的单击事件,您首先需要解决控制台中报告的问题(主要是资源
的“完整性”
错误)

让我们首先解决子资源完整性错误:

使用openssl在jQuery文件位置打开命令行,然后运行:

catFILENAME.js| openssl dgst-sha384-binary | openssl enc-base64-A

其中,FILENAME.js是jQuery文件的名称(在本例中为jQuery.min.js)

使用(通过向所需的内容交付网络(CDN)脚本提供URL并单击哈希按钮)生成哈希

因此,您的预期输出应如下所示:

<script src="https://code.jquery.com/jquery-1.12.4.min.js"
    integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
    crossorigin="anonymous"></script>
您的脚本:

<!-- jQuery approach -->
$(document).ready(function() {
    $("#btnGetData").click(function() {
        console.log("The button was clicked.");
    }); // button click
}); // ready

<!-- or -->

<!-- Pure JavaScript approach -->
window.onload = function() {
    var btnGetData = document.getElementById('btnGetData');
    btnGetData.addEventListener("click", function () {
        console.log("The button was clicked.");
    }); // button click
}; // ready
总之:

$.ajax({
    type: 'GET',

    url: '@Url.Action("GetQuadrantData", "LandingPage")',

    // Should you face any escape character challenge, use 'url' with @Html.Raw()
    //url: '@Html.Raw(@Url.Action("GetQuadrantData", "LandingPage"))',

    console.log(url);

    data: {unit: unitval, begdate: begdateval, enddate: enddateval},

    contentType: 'text/plain',

    cache: false,

    xhrFields: {
        withCredentials: false
    },

    success: function(returneddata) {
        console.log('Successful: ' + returneddata);
    },

    error: function() {
        console.log('hey, boo-boo!');
    }
});

是否打开控制台并检查错误?您可能需要在单击处理程序的第一行输入e.preventDefault()。我似乎还记得我在按钮元素上遇到过类似的问题。jQuery没有定义?很好。。。现在检查JS文件和脚本的顺序:确保在引用jQuery库之后按优先级顺序添加脚本,然后再添加引导JS文件;这将解决您在控制台日志中打印的大多数错误。(请记住在再次运行测试之前清除浏览器缓存,让我们从那里继续进行进一步的故障排除。)这是一个很长的问题,应该相对简单。请参阅更新2。尝试此@allan.p:如果没有Clay使用的检查(不起作用),它肯定会工作,但关键是它是可用的。因此,解决影响要使用的资源(这里是jQuery库)的数据完整性检查错误应该是最有效的解决方案,而不是疏远它。请参阅我的答案应用修复程序以获得详细解释。我在conosle中发出了警报,它运行良好(弹出)。穆罕默德·伊凡:应该考虑;不可忽视。当无效应用或被引用资源的内容(如果被有效应用和访问)被更改时,结果将是错误和/或无法加载外部资源,除非提供了正常的故障切换(加载外部资源的本地副本)。此外,没有必要(未使用)向按钮添加
type=“submit”
,因为JavaScript部分已经处理了预期的行为。查看我的答案以了解详细信息。“您的JS引用最好位于页面内容的末尾,在body标记()关闭之前。”包括css链接引用,还是只包含JS引用?现在,css和js都被添加到标题之后和内联“样式”部分之前;这让我走了一段路;请参阅更新5。仅JS参考。应在正文标记关闭之前(
)。对于CSS引用,
部分可以。将尽快检查您的更新。
public static void Register(HttpConfiguration config)
{
    config.Routes.Clear(); // added this 9/2/2016 at suggestion from http://www.codemag.com/article/1601031
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // I don't know if this is where this should go (from http://stackoverflow.com/questions/34626483/how-to-pass-datatable-via-frombody-to-web-api-post-method-c)
    config.Formatters.Add(new DataTableMediaTypeFormatter());
    config.Formatters.Add(new GenericProduceUsageListMediaTypeFormatter());
}
<button type="submit" class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
<script src='https://code.jquery.com/jquery-1.12.4.min.js' integrity='sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=' crossorigin='anonymous'></script>
<script src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<button class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
window.onload = function() {
    var btnGetData = document.getElementById('btnGetData')
    btnGetData.addEventListener("click", function() {
        alert("Twerking...");
        var unitval = _unit;
        var begdateval = _beginDate;
        var enddateval = _endDate;
        var model = JSON.stringify({
            unit: unitval,
            begdate: begdateval,
            enddate: enddateval
        });
        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetQuadrantData", "LandingPage")',
            data: {
                unit: unitval,
                begdate: begdateval,
                enddate: enddateval
            },
            contentType: 'application/json',
            cache: false,
            success: function(returneddata) {},
            error: function() {
                alert('hey, boo-boo!');
            }
        });
    }); // button click
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">   

    $(document).ready(function () {
        $("#btnGetData").click(function () {
            alert("The button was clicked.");

        }); // button click
    }); // ready
</script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
    integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
    crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
    integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
    crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="path/to/jquery-1.12.4.min.js"><\/script>')</script>
<button class="btn btn-success btn-sm" id="btnGetData" name="btnGetData">SUBMIT</button>
<!-- jQuery approach -->
$(document).ready(function() {
    $("#btnGetData").click(function() {
        console.log("The button was clicked.");
    }); // button click
}); // ready

<!-- or -->

<!-- Pure JavaScript approach -->
window.onload = function() {
    var btnGetData = document.getElementById('btnGetData');
    btnGetData.addEventListener("click", function () {
        console.log("The button was clicked.");
    }); // button click
}; // ready
xhrFields: {
    withCredentials: false
},
$.ajax({
    type: 'GET',

    url: '@Url.Action("GetQuadrantData", "LandingPage")',

    // Should you face any escape character challenge, use 'url' with @Html.Raw()
    //url: '@Html.Raw(@Url.Action("GetQuadrantData", "LandingPage"))',

    console.log(url);

    data: {unit: unitval, begdate: begdateval, enddate: enddateval},

    contentType: 'text/plain',

    cache: false,

    xhrFields: {
        withCredentials: false
    },

    success: function(returneddata) {
        console.log('Successful: ' + returneddata);
    },

    error: function() {
        console.log('hey, boo-boo!');
    }
});