我正在开发一个应用程序,后端用RoR编写,前端完全用javascript / jquery / ajax编写。我的问题是如何将变量传递给我的ajax get请求的url?我的代码:
$(document).ready(function() {
$("button").click(function() {
$.getJSON('http://www.mydomain.com/recipes/1', function(results) {
$('#1').val(results.recipe_name)
$('#2').val(results.author)
$('#3').val(results.level_of_difficulty)
$('#4').val(results.instructions)
$('#5').val(results.activity)
})
})
})
现在,URL的格式为/ recipes /:id,我希望:id是一个变量,这样当我点击"显示"时,数据将正确加载。对于不同的食谱...所以像http://www.mydomain/recipies/recipe_x
提前致谢!
答案 0 :(得分:2)
您可以使用data属性在每个链接上设置配方的ID。然后使用id更改URL。
<a data-id="1">Recipe 1</a>
$("button").click(function(this) {
$.getJSON('http://www.mydomain.com/recipes/' + $(this).data("id")