简体   繁体   English

将data-url属性传递给jQuery ajax url

[英]Pass data-url attribute to jQuery ajax url

I have a form with a data-attribute containing a URL to an API JSON file: 我有一个带有数据属性的表单,其中包含指向API JSON文件的URL:

<form class="product" action="#" data-url="dist/scripts/main.js">
    [...]
</form>

I want to pass the URL from the data attribute into an Ajax call in an external script. 我想将URL从data属性传递到外部脚本中的Ajax调用中。

external.js: external.js:

var apiUrl = $('.product').data('url');
console.log(apiUrl) // This returns the correct URL set above

$.ajax(apiUrl).done(function(data) {
    [...]
});

I even condensed it like this and same result: 我什至这样浓缩它,并得到相同的结果:

$.ajax($('.product').data('url')).done(function(data) {
    [...]
});

When I do this, my doing a feedback loop, possibly because of the (data) parameter that's being used in the ajax function. 当我这样做时,我做一个反馈循环,可能是因为ajax函数中使用了(data)参数。

Error: Cannot read property '0' of undefined referring to a line that contains currentPosition = data.Positions[0].Position; 错误: Cannot read property '0' of undefined引用涉及包含currentPosition = data.Positions[0].Position;

I'm not sure why the URL isn't passing to the ajax function correctly. 我不确定为什么URL无法正确传递给ajax函数。

https://plnkr.co/edit/RT0cHEAjDHFssXg2YbC4?p=preview https://plnkr.co/edit/RT0cHEAjDHFssXg2YbC4?p=preview

It works here - you can see the 404 in console. 它在这里有效-您可以在控制台中看到404。 Make sure you load external.js after the dom loads. 确保在dom加载后加载external.js。 In this case it's just script.js Or you can use the $( document ).ready() 在这种情况下,这只是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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM