将 data-url 属性传递给 jQuery ajax url
Pass data-url attribute to jQuery ajax url
我有一个包含 URL 到 API JSON 文件的数据属性的表单:
<form class="product" action="#" data-url="dist/scripts/main.js">
[...]
</form>
我想将 URL 从数据属性传递到外部脚本中的 Ajax 调用。
external.js:
var apiUrl = $('.product').data('url');
console.log(apiUrl) // This returns the correct URL set above
$.ajax(apiUrl).done(function(data) {
[...]
});
我什至像这样压缩它,结果相同:
$.ajax($('.product').data('url')).done(function(data) {
[...]
});
当我这样做时,我在做一个反馈循环,可能是因为 ajax 函数中使用了 (data) 参数。
错误:Cannot read property '0' of undefined
引用包含 currentPosition = data.Positions[0].Position;
的行
我不确定为什么 URL 没有正确传递给 ajax 函数。
https://plnkr.co/edit/RT0cHEAjDHFssXg2YbC4?p=preview
它在这里工作 - 你可以在控制台中看到 404。确保在 dom 加载之后加载 external.js。在这种情况下,它只是 script.js 或者您可以使用 $( document ).ready()
<html>
<head>
<script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello Plunker!</h1>
<form class="product" action="#" data-url="dist/scripts/main.js">
<input type="text">
</form>
<script src="script.js"></script>
</body>
</html>
我有一个包含 URL 到 API JSON 文件的数据属性的表单:
<form class="product" action="#" data-url="dist/scripts/main.js">
[...]
</form>
我想将 URL 从数据属性传递到外部脚本中的 Ajax 调用。
external.js:
var apiUrl = $('.product').data('url');
console.log(apiUrl) // This returns the correct URL set above
$.ajax(apiUrl).done(function(data) {
[...]
});
我什至像这样压缩它,结果相同:
$.ajax($('.product').data('url')).done(function(data) {
[...]
});
当我这样做时,我在做一个反馈循环,可能是因为 ajax 函数中使用了 (data) 参数。
错误:Cannot read property '0' of undefined
引用包含 currentPosition = data.Positions[0].Position;
我不确定为什么 URL 没有正确传递给 ajax 函数。
https://plnkr.co/edit/RT0cHEAjDHFssXg2YbC4?p=preview
它在这里工作 - 你可以在控制台中看到 404。确保在 dom 加载之后加载 external.js。在这种情况下,它只是 script.js 或者您可以使用 $( document ).ready()
<html>
<head>
<script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello Plunker!</h1>
<form class="product" action="#" data-url="dist/scripts/main.js">
<input type="text">
</form>
<script src="script.js"></script>
</body>
</html>