我有这个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”) 分配适当的值。
那么为什么单击按钮,声明如下:
<button class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
......什么都不做?
这是要添加的脚本(来自View&gt; Page Source):
<script>$(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!');}});});});</script>
这可能不相关(但无论如何),但这是我想从该按钮点击调用的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"
)
};
}
这是来自控制台的错误转储:
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)
我正在添加jQuery;我在“头部”部分有这个:
<script src='https://code.jquery.com/jquery-1.12.4.min.js' integrity='sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=' crossorigin='anonymous'></script>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' rel='stylesheet' />
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>
在这里加入一些建议,这是我的运行页面来源(按钮仍无响应):
<html style='margin-top:20;margin-left:60;margin-right:60; -webkit-box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .25);box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .5);padding-left: 1px;padding-right: 1px;padding-bottom: 15px;'><head><title>Available Reports for ABUELOS</title><script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' rel='stylesheet' /><script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script><link href="~/Content/Site.css" rel="stylesheet" /><![endif]--><style>body {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;}</style></head><body><div class="jumbotronjr"><div class="col-md-3" style="margin-top: 0.6cm"><img src="http://www.proactusa.com/wp-content/themes/proact/images/pa_logo_notag.png" height="86" width="133" alt="PRO*ACT usa logo"></div><div class="col-md-9"><label class="titletext" style="margin-top: 0.2cm;">Customer Dashboard</label><br/><label class='titletextjr' style='margin-top: -2.2cm;'>ABUELOS</label><label> for the week of August 21 </label><input class="smalldatepicker" type="date" id="datepicker" name="daterangefrom" value="2016-08-21"></input><label> to </label><input type="date" class="smalldatepicker" id="datepicker" name="daterangeto" value="2016-08-27"></input><button type="button" class="btn green smallbutton" id="btnGetData" name="btnGetData">GO</button></div><div class="row"><div class="col-md-12"><hr /></div></div><div class="row"><div class="col-md-12"></div></div><div class="row"><div class="col-md-6"><div class="topleft"><h2 class="sectiontext">Top 10 Items Purchased</h2><table><tr><th>Item Code</th><th>Description</th><th class="rightjustifytext">Qty</th></tr><tr><td>156100</td><td>ONIONS, YELLOW JUMBO 50#</td><td class="rightjustifytext">362</td></tr><tr><td>226150</td><td>AVOCADOS, ABUELOS-HASS 70CT 23#</td><td class="rightjustifytext">358</td></tr><tr><td>163150</td><td>PEPPERS, ANAHEIM GREEN 20#</td><td class="rightjustifytext">282</td></tr><tr><td>176000</td><td>POTATOES, RED A 50#</td><td class="rightjustifytext">266</td></tr><tr><td>188301</td><td>TOMATOES, ROMA HOT HOUSE 25#</td><td class="rightjustifytext">230</td></tr><tr><td>167150</td><td>PEPPERS, POBLANO 18 - 20#</td><td class="rightjustifytext">202</td></tr><tr><td>189300</td><td>TOMATILLOS, 30# NO HUSK</td><td class="rightjustifytext">168</td></tr><tr><td>170150</td><td>PEPPERS, GRN CH 1&1/9 BU (18-26#)</td><td class="rightjustifytext">163</td></tr><tr><td>122500</td><td>LETTUCE, ICEBERG LINER 24 CT</td><td class="rightjustifytext">133</td></tr><tr><td>127100</td><td>LETTUCE, ROMAINE 24 CT </td><td class="rightjustifytext">129</td></tr></table></div></div><div class="col-md-6"><div class="topright"><h2 class="sectiontext">Pricing Exceptions - Weekly Recap</h2><label class="redfont" style="font-size: 12px">Red denotes Contract Item Overages</label></br><label style="font-size: 12px">For Weyand on the pricing week of - 7/31/2016</label><table><tr><th>PRO*ACT Member</th><th class="rightjustifytext">Total Occurrences of Summary Items</th><th class="rightjustifytext">Total Summary Exceptions</th><th class="rightjustifytext">Total Percentage of Summary Exceptions</th></tr><tr><td style="width:30%">Stern</td><td style="width:23%" class="rightjustifytext">205</td><td style="width:23%" class="rightjustifytext">2</td><td style="width:24%" class="rightjustifytext">99.02%</td></tr><tr><td>Hardies Dallas</td><td class="rightjustifytext">1,597</td><td class="rightjustifytext">0</td><td class="rightjustifytext">100.00%</td></tr><tr><td>Hardies South</td><td class="rightjustifytext">612</td><td class="rightjustifytext">1</td><td class="rightjustifytext">99.84%</td></tr><tr><td>Go Fresh</td><td class="rightjustifytext">482</td><td class="rightjustifytext">0</td><td class="rightjustifytext">100.00%</td></tr><tr><td>Segovias</td><td class="rightjustifytext">1,360</td><td class="rightjustifytext">2</td><td class="rightjustifytext">99.85%</td></tr><tr><td>Potato Spec</td><td class="rightjustifytext">1,605</td><td class="rightjustifytext">0</td><td class="rightjustifytext">100.00%</td></tr><tr><td class="rightjustifytext bold">TOTAL</td><td class="rightjustifytext bold">5,861</td><td class="rightjustifytext bold">5</td><td class="rightjustifytext bold">99.79%</td></tr></table></div></div></div><div class="row"><div class="col-md-6"><div class="bottomleft"><h2 class="sectiontext">Forecasted Spend - $9,814.81</h2><table><tr><th>Item Code</th><th class="rightjustifytext">Last Week's Usage</th><th class="rightjustifytext">This Week's Price</th><th class="rightjustifytext">Forecasted Spend</th></tr><tr><td>261650</td><td class="rightjustifytext">49</td><td class="rightjustifytext">3.14</td><td class="rightjustifytext">153.86</td></tr><tr><td>231083</td><td class="rightjustifytext">52</td><td class="rightjustifytext">1.25</td><td class="rightjustifytext">65.00</td></tr><tr><td>398980</td><td class="rightjustifytext">46</td><td class="rightjustifytext">4.95</td><td class="rightjustifytext">227.70</td></tr><tr><td>351135</td><td class="rightjustifytext">40</td><td class="rightjustifytext">0.75</td><td class="rightjustifytext">30.00</td></tr><tr><td>398036</td><td class="rightjustifytext">42</td><td class="rightjustifytext">3.00</td><td class="rightjustifytext">126.00</td></tr><tr><td>208110</td><td class="rightjustifytext">42</td><td class="rightjustifytext">2.50</td><td class="rightjustifytext">105.00</td></tr><tr><td>102800</td><td class="rightjustifytext">1835</td><td class="rightjustifytext">2.25</td><td class="rightjustifytext">4,128.75</td></tr><tr><td>367050</td><td class="rightjustifytext">1910</td><td class="rightjustifytext">1.95</td><td class="rightjustifytext">3,724.50</td></tr><tr><td>173100</td><td class="rightjustifytext">66</td><td class="rightjustifytext">19.00</td><td class="rightjustifytext">1,254.00</td></tr><tr><td class="bold">TOTAL</td><td class="bold rightjustifytext">4082</td><td class="bold rightjustifytext">--</td><td class="bold rightjustifytext">$9,814.81</td></tr></table></div></div><div class="col-md-6"><div class="bottomright"><h2 class="sectiontext">Delivery Performance</h2><table><tr><th>PRO*ACT Distributor</th><th>Restaurant Location</th><th class="rightjustifytext">Avg Order Amount</th><th class="rightjustifytext">Avg Package Count</th><th class="rightjustifytext">Total Sales</th></tr><tr><td>Sunrise FL</td><td>A1A ALEWORKS - #4405 - ST. AUGUSTINE</td><td class="rightjustifytext">$475.78</td><td class="rightjustifytext">28.50</td><td class="rightjustifytext">$1,903.10</td></tr><tr><td>Sunrise FL</td><td>RAGTIME TAVERN - #4404 - ATLANTIC BEACH</td><td class="rightjustifytext">$221.46</td><td class="rightjustifytext">17.50</td><td class="rightjustifytext">$885.82</td></tr><tr><td>Sunrise FL</td><td>SEVEN BRIDGES - #4403 - JACKSONVILLE</td><td class="rightjustifytext">$367.49</td><td class="rightjustifytext">22.67</td><td class="rightjustifytext">$1,102.47</td></tr><tr><td>T&T</td><td>BIG RIVER - #4201 - CHATTANOOGA</td><td class="rightjustifytext">$396.06</td><td class="rightjustifytext">22.83</td><td class="rightjustifytext">$2,376.34</td></tr><tr><td>T&T</td><td>BIG RIVER - #4205 - HAMILTON PL</td><td class="rightjustifytext">$424.74</td><td class="rightjustifytext">26.00</td><td class="rightjustifytext">$1,698.95</td></tr><tr><td class="bold">TOTAL</td><td></td><td class="bold rightjustifytext">3,770.42</td><td class="bold rightjustifytext">23.50</td><td class="bold rightjustifytext">$1,592.60</td></tr></table></div></div></div></div><script>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!');}});});</script></div></body></html>
为了尝试验证问题是我用C#动态创建html(和javascript),我将脚本添加到Index.cshtml文件(这是初始页面,并且在运行时不会被修改) ):
. . .
</style>
<script>
$(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!');
}
});
});
});
</script>
</head>
. . .
以下是 LandingPageController:ApiController 类中的方法,我试图用该AJAX调用:
[Route("{unit}/{begdate}/{enddate}")]
public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
{
_unit = unit;
. . .
这样做,我做看到“It works”警报,然后是“嘿,嘘!”也是,从javascript按钮单击事件处理程序。 “_unit = unit;”的断点永远不会到达。这就是为什么我看到“boo-boo”的消息,我估计,但我不知道为什么它没有达到。
Url.Action args仍然被转换/翻译错误;在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>
...所以这个:
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;
在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。
如果我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推荐的那样:<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
有了这个(在将javascript引用移到底部之后,就在“BTW”之上):
. . .
</style>
<script>
$(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
</script>
</head>
. . .
...我在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!
这是我在\ 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());
}
这里有什么不对吗?
答案 0 :(得分:8)
为了成功触及按钮上的click事件,首先需要解决控制台中报告的问题(主要是资源'integrity'
错误)。
让我们从解决子资源完整性错误开始:
在jQuery文件位置使用 openssl 打开命令行并运行:
cat FILENAME.js | openssl dgst -sha384 -binary | openssl enc -base64 -A
其中,FILENAME.js是您的jQuery文件的名称(在您的情况下为:jquery.min.js。)
或
利用SRI Hash Generator(通过提供所需内容传送网络(CDN)脚本的URL并单击HASH按钮)生成Subresource Integrity (SRI)哈希。
因此,您的预期输出应如下:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
crossorigin="anonymous"></script>
注意:完整性属性使浏览器能够检查并确保如果引用的资源文件的内容与生成SRI哈希时的内容不同,则不会加载它。 < / p>
然后,您应该考虑通过在您的服务器上托管jQuery文件的副本来进行优雅的故障转移,以便在您引用的CDN版本的内容被更改时使用。
检查是否已定义jQuery,如果没有,则引用故障转移。
<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>
请记住在引用JavaScript(JS)文件时坚持使用此优先级顺序:
注意:您的JS 引用最好位于页面内容的末尾,在正文标记结束之前(</body>
)。
应用上述修补程序后,当您单击按钮时,您将成功进入控制台:The button was clicked.
(请参阅下面的代码段)。
您的按钮:
<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
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!');
}
});
答案 1 :(得分:2)
尝试这一点,它只是使用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
}
答案 2 :(得分:1)
如果您要提交表单,请添加如下按钮类型:
<button type="submit" class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
<强>更新强>
来自您的&#34;更新2&#34;改变第一行:
<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而不会出现任何错误。感谢
答案 3 :(得分:1)
您的代码适用于我:http://codepen.io/danielvaughn/pen/jrNoko
您确定要正确导入jQuery吗?如果没有,请在控制台中运行一些jquery函数以确保它有效。
<button class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
答案 4 :(得分:1)
老兄,有一个问题:你确定你正确地包含了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>