【问题标题】:How to set the url while passing array from jquery to python function?将数组从jquery传递给python函数时如何设置url?
【发布时间】:2021-02-19 05:15:49
【问题描述】:

如何将参数从 jquery 传递给 python 方法?

JQUERY

const fruits = ['Apple', 'Mango', 'Orange', 'Grapes']
   function sendfruitstoPython() {
       $.ajax({
       url: 'Getfruits',
       type: "POST",
       data: { Fruit : fruits } ,
       success: callbackFunc
    });

function callbackFunc(response) {
        console.log("demo");
    }
}

Python

def Getfruits(request):
    demo = request.GET.getlist('Fruit')
    print("this is ", demo)

输出 这是[]

网址格式:

path('Getfruits', views.Getfruits, name='Getfruits')

它也试过这个......

JQUERY

function sendfruitstoPython() {
       $.ajax({
       url: 'Getfruits'+ fruits ,
       type: "POST",
       success: callbackFunc
    });

PYTHON
def def Getfruits(request, fruits) :
    demo = request.POST.getlist('fruits')
    print("this is ", demo)
   
URL PATTERN
path(r'^Getfruits/(?P<Fruit>\w+)/$', views.Getfruits, name='Fruit'),

这给了我错误,他当前的路径 Extractor/Getfruits[object set] 与其中任何一个都不匹配。

在控制台中我得到了这个.. 未找到:/Extractor/Getfruits[对象集] [2020 年 11 月 9 日 18:27:56]“POST /Extractor/Getfruits[object%20Set] HTTP/1.1”404 3340

【问题讨论】:

    标签: jquery python-3.x django ajax url-parameters


    【解决方案1】:

    JQUERY

    const fruits = ['Apple', 'Mango', 'Orange', 'Grapes']
    function sendfruitstoPython() {
          var selfruit = Array.from(fruits);    
           $.ajax({
           url: 'Getfruits/'+selfruit,
           type: "POST",
           success: callbackFunc
        });
    
    function callbackFunc(response) {
            console.log("demo");
        }
    }
    

    PYTHON URL 模式

    path('Getfruits/<selfruit>', views.Getfruits)
    
    

    Python 方法

    @csrf_exempt    
    def Getfruits(request, selfruit):
    li = list(selfruit.split(","))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      相关资源
      最近更新 更多