【发布时间】:2018-07-20 06:35:12
【问题描述】:
我认为这是前端的问题,我对前端不熟悉。所以,这可能不是最好的方法,欢迎提出建议。
我需要从通过 django-rest-framework 开发的 rest api 中获取一些数据,并将其放入表单的输入字段中。
所以,这是代码,
function getcharmids(){
var get_url = "http://localhost:8000/get_charm_ids/" + name; # name I am declaring in the django template
console.log('clicked');
$.ajax({
type: 'GET',
dataType: "json",
url: get_url,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
accept: "application/json",
success: function(data){
var charm_input = document.getElementById('id_charm_ids');
console.log(charm_input.value);
charm_input.value = data.charm_ids;
},
});
};
所以,它确实调用了 URL,但带有额外的参数。
它应该调用http://localhost:8000/get_charm_ids/Kasam09
但它调用/get_charm_ids/Shakti_02?callback=jQuery111009547658997639622_1518179689207&_=1518179689208
因此,由于额外的参数,我的后端无法处理此请求。这个问题的解决方法是什么?
通过 jquery 调用 apis 的正确方法是什么?
或者还有什么好的方法吗?
编辑 -
这是我的 api urls.py 文件,
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^get_data/(?P<vid>(.*?))$', views.get_data),
url(r'^get_charm_ids/(?P<vid>(.*?))$', views.get_charm_ids),
]
这是我的views.py文件,
@api_view(['GET'])
def get_data(request, vid):
if request.method == 'GET':
#here is my code
return Response({'data':'a1,b2,c3,d4'})
@api_view(['GET'])
def get_charm_ids(request, vid):
if request.method == 'GET':
#here is my code
return Response({'charm_ids':'1,2,3,4,5,6'})
【问题讨论】:
-
让我们了解您如何构建 html。似乎每个循环都重新分配了名称,或者它没有得到您想要获得的预期名称。它还可以帮助我们确定额外的回调参数来自哪里。
-
我也很想知道为什么您的后端“无法处理此请求”。为什么它不忽略它不知道的参数?你得到什么错误?
标签: javascript jquery django django-rest-framework