1

我使用 django-tastypie 使用 GET、POST、PUT、DELETE 方法,当客户端和服务器都来自同一个域时,它们工作顺利,但是如果我从不同域发出请求,则什么也没有发生。

有什么线索吗?

模型.py

from django.db import models
class Entry(models.Model):
    title = models.CharField(max_length=30)
    body = models.CharField(max_length=40)
    pub_date = models.DateField()
    slug=models.CharField(max_length=30)

资源.py

from django.contrib.auth.models import User
from tastypie.authorization import Authorization
from tastypie import fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS  
from myapp.models import Entry


class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
        filtering = {
        'username': ALL,
        }


class EntryResource(ModelResource):

    class Meta:
    queryset = Entry.objects.all()
    resource_name = 'entry'
    authorization = Authorization()
    filtering = {
        'user': ALL_WITH_RELATIONS,
        'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'],
        }

网址.py

from django.views.generic.simple import direct_to_template
from django.conf.urls.defaults import *
from tastypie.api import Api
from myapp.resources import EntryResource, UserResource

v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(EntryResource())

urlpatterns = patterns('',
# The normal jazz here...
     (r'^api/', include(v1_api.urls)),
     (r'^basic/$', direct_to_template, {'template': 'todos/test.html'})
)

模板文件如下

<!DOCTYPE html>
<html>
    <head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript">
  jQuery(document).ready(function($) {
      var data = JSON.stringify({
      "body": "This will prbbly be my lst edited  post.",
      "pub_date": "2011-05-22T00:46:38",
       "slug": "another-post",
      "title": "Another Post",

     });
  $.ajax({
        url: "http://localhost:8000/api/v1/entry/1/?format=json",
        type: 'PUT',
            contentType: 'application/json',
        data: data,
        dataType: 'json',
        processData: false,
        success:function(data) { 
            alert(data);
            },
        error : function(data){
            alert('error')
            },  
        })
  }) 

 </script>
    </head>
    <body>
body content goes here 
    </body>
</html>

现在,当我运行http://localhost:8000/basic时,它非常适合 CRUD

后来我安装了apache服务器并复制了那个basic.html。当我运行http://localhost:81/basic.html时,服务器不接受 json 数据。我同时运行了 apache 和 python 服务器。

4

1 回答 1

2

您需要将您的客户端和服务器设置为跨域 ajax。

在 jquery 中,您可以crossDomain : true$.ajax()调用中设置(请参阅http://api.jquery.com/jQuery.ajax/

在服务器端,您需要设置几个接受标头 http://enable-cors.org/

您可以通过查看 CORS 规范了解有关跨域请求的更多信息:http: //www.w3.org/TR/cors/

于 2012-05-10T07:47:45.643 回答