2014-01-10 33 views

回答

1

你只需要以下面的格式对tastypie api url进行ajax调用。

$.ajax({ 
     type: 'POST', 
     url: site_url+'api/v2/user/login/', 
     data: '{"username": "developer", "password":"imagine2"}', 
     processData: false, 
     crossDomain: true, 
     success: function (response, textStatus, xhr) { 
       console.log('jquery worked'); 
       //results=JSON.stringify(response); 
       setCookie("sessionid", response.sessionid); 
       setCookie("app_version", response.app_version); 
       window.location.href = 'home/'; 
       $('#overlay').hide(); 
     }, 
     error: function (res) { 
     msg = (res.responseText) ? res.responseText : res.statusText; 
     console.log(msg+",res.status="+res.status); 
     alert(msg); 

     }, 
     dataType: "json", 
     contentType: "application/json; charset=utf-8" 
    }); 

此外,您还需要启用跨域。

0

有多种方法可以做到这一点。由于您使用的是tastypie的API,我建议您不要提交表单本身,而是在用JavaScript提交表单之前提取表单数据。在提交时,您将要在请求正文中提交的数据传递给您的API端点。

举个例子,你可能对博客条目的API端点,可以说其http://example.com/api/v1/entry。考虑到你的API允许跨域请求(例如,通过CORS),你可以做一些简单的,因为这为“提交”的形式(例如创建一个新的条目):

$('#myForm #mySubmitButton').click(function() { 
    $.post('http://example.com/api/v1/entry', $('#myForm').serialize(), function(data) { 
     // deal with the response data 
    } 
}); 

我不知道tastypie支持这种数据结构。这方面的一个长一点的版本可能是做这样的事情(在这里我肯定tastypie不支持它),它提交的数据作为JSON:

$('#myForm #mySubmitButton').click(function() { 
    var data = {'title': $('#myForm #titleInput').val(), 'description': $('#myForm #descriptionInput').val()}; 
    $.post('http://example.com/api/v1/entry', data, function(data) { 
     // deal with the response data 
    } 
}); 

这个例子不处理表单验证,错误处理等等。您可以查看tastypie validation以获取更多详细信息,也可能会使用HTML5添加前端特定的验证。我还建议您使用更复杂的JavaScript框架,如AngularJS,用于单页应用程序,如PhoneGap应用程序。当JQuery增长时,它很快就会膨胀你的应用程序。

相关问题