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

我有这个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方法没有被调用 – 这个处理程序显然根本没有触发,因为我看不到任何警报(既没有“ 按钮被点击也没有 ”也没有“ 嘿,嘘! ”)。

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

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

  

…没做什么?

这是要添加的脚本(从View> Page Source):

 $(document).ready(function() {$("#btnGetData").click(function() {alert("The button was clicked.");var unitval = ABUELOS;var begdateval = 2016-08-21;var enddateval = 2016-08-27;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!');}});});}); 

这可能不相关(但无论如何),但这是我想从该按钮点击调用的REST方法:

 public class LandingPageController : ApiController . . . [Route("{unit}/{begdate}/{enddate}")] public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate) { _unit = unit; _beginDate = begdate; _endDate = enddate; string beginningHtml = GetBeginningHTML(); // This could be called from any page to reuse the same "header" string top10ItemsPurchasedHtml = GetTop10ItemsPurchasedHTML(); string pricingExceptionsHtml = GetPricingExceptionsHTML(); string forecastedSpendHtml = GetForecastedSpendHTML(); string deliveryPerformanceHtml = GetDeliveryPerformanceHTML(); string endingHtml = GetEndingHTML(); String HtmlToDisplay = string.Format("{0}{1}{2}{3}{4}{5}", beginningHtml, top10ItemsPurchasedHtml, pricingExceptionsHtml, forecastedSpendHtml, deliveryPerformanceHtml, endingHtml); return new HttpResponseMessage() { Content = new StringContent( HtmlToDisplay, Encoding.UTF8, "text/html" ) }; } 

UPDATE

这是来自控制台的错误转储:

 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; 我在“头部”部分有这个:

    

更新3

在这里加入一些建议,这是我的运行页面源(按钮仍无响应):

 Available Reports for ABUELOSbody {padding-top: 20px;padding-bottom: 20px;background-color: white;}hr {border: 0;height: 1px;color: navy;background: #333;margin-left:-4;margin-right:-4;}table {font-family: arial, sans-serif;font-size: 13px;border-collapse: collapse;width: 100%;}td, th {border: 1px solid #dddddd;text-align: left;padding: 8px;}label { white-space: pre; }tr:nth-child(even) {background-color: #dddddd;}.body-content {-webkit-box-shadow: -1px 0 5px 0 #000000;-webkit-box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .25);box-shadow: -1px 0 5px 0 #000000;box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .5);padding-left: 1px;padding-right: 1px;padding-bottom: 15px;}.jumbotronjr {padding: 2px;margin-top: -12px;margin-bottom: -24px;font-size: 21px;font-weight: 200;color: inherit;background-color: white;}.titletext {font-size: 2.1em;color: darkgreen;font-family: Candara, Calibri, Cambria, serif;margin-left: -32px;}.titletextjr {font-size: 1.4em;color: darkgreen;font-family: Candara, Calibri, Cambria, serif;margin-left: -32px;}.cccsfont {font-size: 0.25em !important;font-family: Calibri, Candara, Cambria, serif !important;}.smalldatepicker {font-size: 12px;font-weight: 100;}.smallbutton {font-size: 11px;font-weight: 100;margin-left: 16;}.addltopmargin {margin-top: 8px;}.sectiontext {font-size: 1em;font-weight: bold;font-family: Candara, Calibri, Cambria, serif;color: green;margin-top: -4px;}.bottommarginbreathingroom {margin-bottom: 2px;}.submitbtnmargins {margin-top: -4px !important;margin-left: 8px !important;margin-bottom: 8px;}.btn.green{background-color: darkgreen;color: white;}.redfont {color: red;}.bold {font-weight: bold;}.rightjustifytext {text-align: right;}.topleft {margin-top: -8px;margin-left: 12px;margin-bottom: 8px;padding: 16px;border:1px solid black;}.topright {margin-top: -8px;margin-right: 12px;margin-bottom: 8px;margin-left: -12px;padding: 16px;border:1px solid black;}.bottomleft {margin-left: 12px;padding: 16px;border:1px solid black;}.bottomright {margin-right: 12px;margin-left: -12px;padding: 16px;border:1px solid black;}.topright, .topleft {height: 408px; }.bottomright, .bottomleft {height: 408px; }.leftmargin12 {margin-left: 12px !important;}
PRO*ACT usa logo


Top 10 Items Purchased

Item CodeDescriptionQty
156100ONIONS, YELLOW JUMBO 50#362
226150AVOCADOS, ABUELOS-HASS 70CT 23#358
163150PEPPERS, ANAHEIM GREEN 20#282
176000POTATOES, RED A 50#266
188301TOMATOES, ROMA HOT HOUSE 25#230
167150PEPPERS, POBLANO 18 - 20#202
189300TOMATILLOS, 30# NO HUSK168
170150PEPPERS, GRN CH 1&1/9 BU (18-26#)163
122500LETTUCE, ICEBERG LINER 24 CT133
127100LETTUCE, ROMAINE 24 CT 129

Pricing Exceptions - Weekly Recap


PRO*ACT MemberTotal Occurrences of Summary ItemsTotal Summary ExceptionsTotal Percentage of Summary Exceptions
Stern205299.02%
Hardies Dallas1,5970100.00%
Hardies South612199.84%
Go Fresh4820100.00%
Segovias1,360299.85%
Potato Spec1,6050100.00%
TOTAL5,861599.79%

Forecasted Spend - $9,814.81

Item CodeLast Week's UsageThis Week's PriceForecasted Spend
261650493.14153.86
231083521.2565.00
398980464.95227.70
351135400.7530.00
398036423.00126.00
208110422.50105.00
10280018352.254,128.75
36705019101.953,724.50
1731006619.001,254.00
TOTAL4082--$9,814.81

Delivery Performance

PRO*ACT DistributorRestaurant LocationAvg Order AmountAvg Package CountTotal Sales
Sunrise FLA1A ALEWORKS - #4405 - ST. AUGUSTINE$475.7828.50$1,903.10
Sunrise FLRAGTIME TAVERN - #4404 - ATLANTIC BEACH$221.4617.50$885.82
Sunrise FLSEVEN BRIDGES - #4403 - JACKSONVILLE$367.4922.67$1,102.47
T&TBIG RIVER - #4201 - CHATTANOOGA$396.0622.83$2,376.34
T&TBIG RIVER - #4205 - HAMILTON PL$424.7426.00$1,698.95
TOTAL3,770.4223.50$1,592.60
window.onload = function(){var btnGetData = document.getElementById('btnGetData');btnGetData.addEventListener("click", function () {alert("Twerking...");var unitval = ABUELOS;var begdateval = 2016-08-21;var enddateval = 2016-08-27;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!');}});});

更新4

只是为了validation问题是我用C#动态创建html(和javascript),我将脚本添加到Index.cshtml文件(这是初始页面,并且在运行时不会被修改):

 . . .   $(function () { var btnGetData = document.getElementById('btnGetData'); btnGetData.addEventListener("click", function () { alert("It works"); var unitval = 'Abuelos'; var begdateval = '2016-08-07'; var enddateval = '2016-08-13'; $.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!'); } }); }); });   . . . 

这是LandingPageController中的方法我试图用这个AJAX调用的ApiController类:

 [Route("{unit}/{begdate}/{enddate}")] public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate) { _unit = unit; . . . 

这样做,我确实看到了“It works”警报,然后是“嘿,嘘声!” 也是,从javascript按钮单击事件处理程序。 “_unit = unit;”的断点 永远不会到达。 这就是为什么我看到“boo-boo”的消息,我估计,但我不知道为什么它没有达到。

更新5

Url.Action args仍然被转换/翻译错误; 在Chrome开发者工具中,它显示:

  $(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  

…所以这:

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

…正在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添加一些随机数据值):

 $(document).ready(function () { $("#btnGetData").click(function () { $.ajax({ type: 'GET', url: '@Url.Action("GetQuadrantData", "LandingPage")', data: {unit: 'ABUELOS', begdate: '2016-08-25', enddate: '2016-08-31'}, 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 

…我仍然将“boo-boo”msg写入控制台并且我的控制器中的断点未被命中,大概是因为通过Url.Action()方法生成了错误的url。

更新7

如果我kludgily /实验性地将ajax调用更改为this,则用原始url替换Url.Action和数据:

 $(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 

.. 我确实到达了Controller中的断点,但页面上的url没有改变,页面上的数据(html)也没有更新。

顺便说一句,我确实改变了对jquery的引用,正如nyedidikeke推荐的那样:

  

更新8

有了这个(在将javascript引用移动到底部之后,就在“BTW”之上):

 . . .   $(document).ready(function () { $("#btnGetData").click(function () { $.ajax({ type: 'GET', url: '@Url.Action("GetQuadrantData", "LandingPage")', data: { unit: 'ABUELOS', begdate: '2016-08-25', enddate: '2016-08-31' }, 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   . . . 

…我在Chrome Dev Tools的控制台中得到了这个:

 http://localhost:52194/LandingPage/GetQuadrantData?unit=ABUELOS&begdate=2016-08-25&enddate=2016-08-31&_=1473095349071 Failed to load resource: the server responded with a status of 404 (Not Found) hey, boo-boo! 

更新9

这是我在\ App_Start \ WebApiConfig.cs中的Register方法:

 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()); } 

这里有什么不对吗?

为了成功访问按钮上的click事件,首先需要解决控制台中报告的问题(主要是资源'integrity'错误)。

我们首先解决Subresource Integrity错误:

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

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

其中,FILENAME.js是您的jQuery文件的名称(在您的情况下为:jquery.min.js。)

要么

利用SRI哈希生成器 (通过提供所需内容交付网络(CDN)脚本的URL并单击HASH按钮)生成子资源完整性(SRI)哈希。

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

  

注意:integrity属性允许浏览器检查并确保如果引用的资源文件的内容与生成SRI哈希时的内容不同,则不会加载它。

然后,您应该通过在服务器上托管jQuery文件的副本来考虑优雅的故障转移,以便在您引用的CDN版本的内容被更改时使用。

这样做是否检查jQuery是否已定义,如果没有,则引用您的故障转移。

   

在引用JavaScript(JS)文件时,请记住坚持此优先级顺序:

  1. jQuery库,
  2. 然后是Bootstrap JS文件
  3. 您的自定义JS文件,如果有的话。

注意:您的JS 引用应该最好位于页面内容的末尾,在正文标记( )结束之前。

完成上述修复后,您将成功进入控制台: The button was clicked. 当您单击按钮时(请参阅下面的代码段)。

你的按钮:

  

你的脚本:

  $(document).ready(function() { $("#btnGetData").click(function() { console.log("The button was clicked."); }); // button click }); // ready   window.onload = function() { var btnGetData = document.getElementById('btnGetData'); btnGetData.addEventListener("click", function () { console.log("The button was clicked."); }); // button click }; // ready 

jQuery和纯JavaScript方法现在都可以工作,并且可以在您的预期外部资源(jQuery库)上运行完整性测试时访问您的按钮,并且具有优雅的故障转移选项,可以继续进行。

注意:jQuery方法失败了,因为没有声明jQuery库,因为您的SRI检查失败,没有可用的故障转移仍然加载jQuery库。 这没有 The button was clicked. hey, boo-boo! 成功到达按钮上的单击事件和/或单击事件,到您的jQuery AJAX错误函数。

继续进一步,在jQuery AJAX调用中使用contentType: 'text/plain'而不是contentType: 'application/json'因为您期望纯HTML ,而不是JSON响应并设置withCredentials: false (除非您的服务器必须使用标头响应)作为xhrFields声明下的附加属性(请参阅下面的代码段)。

 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!'); } }); 

试试这个,它只是使用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 } 

您的代码适用于我: http : //codepen.io/danielvaughn/pen/jrNoko

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

  

老兄,有一个问题:你确定你正确地包含了jquery库吗?

我尝试了这个并且它有效

   

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

  

UPDATE

从您的“更新2”更改第一行:

  

对此:

  

我们不需要在这里检查jquery文件的完整性,所以通过删除你将能够运行jquery没有任何错误。 谢谢