2014-01-10 34 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增長時,它很快就會膨脹你的應用程序。

相關問題