2016-11-21 16 views
0

我有一個包含一個URL的API JSON文件中的數據屬性的一種形式:傳遞數據url屬性jQuery的AJAX網址

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

我想通過從數據url屬性爲阿賈克斯調用外部腳本。

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函數中使用的參數。

錯誤:Cannot read property '0' of undefined指的是包含currentPosition = data.Positions[0].Position;

我不知道爲什麼網址不流通的AJAX功能正確的線路。

+0

您的html文件中的external.js在哪裏?確保在加載dom後加載它。 – Garuuk

+0

@Garuuk它在結束標籤前的頁面底部。 ajax功能包含在文檔就緒功能中。 – micah

+0

檢查您的控制檯。你看到一個API調用正在進行嗎?您的ajax是由按鈕/偵聽器事件調用的嗎? – Garuuk

回答

1

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

它的工作原理在這裏 - 你可以在控制檯中看到404。確保在加載dom之後加載external.js。在這種情況下,它只是script.js或者您可以使用$(document).ready()

<html> 

    <head> 
    <script data-require="[email protected]*" 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>