JQuery, send JSON object using GET method

前端 未结 4 1919
梦如初夏
梦如初夏 2020-12-14 15:41

I am trying to send a json object using GET method. My code:

$.ajax({
           url: \"/api/endpoint\",
           type: \"GET\",
           data: {\"sort\"         


        
相关标签:
4条回答
  • 2020-12-14 16:10

    GET requests (at least usually) do not have a message body. As mentioned in the docs, jQuery appends data of GET requests to the url parameters. You should be able to read your sort parameter from there with your server application.

    BTW, no user agent will allow you to set the Content-Length header - it will (and must) be done automatically depending on the sent data.

    0 讨论(0)
  • 2020-12-14 16:16

    There are a few places where you have gone a bit wrong.

    • It is not CONTENT_LENGTH, its Content-Length.
    • Do not set Content-Length header, the browser will do it for you.
    • Get request has content-length = 0.

    Something like the below should work for you:

    $.ajax({
         url: "/api/endpoint?parameters="+encodeURIComponent(JSON.stringify({"sort":"date"})),
         type: "GET",
         ...
    });
    
    0 讨论(0)
  • 2020-12-14 16:17

    As mentioned by Bergi, the data is converted by jQuery.ajax() to request parameters. From jQuery 1.7.2:

    // Determine if request has content
    s.hasContent = !rnoContent.test( s.type );    --> false when s.type == "GET'
    

    ...

    if ( !s.hasContent ) {
        // If data is available, append data to url
        if ( s.data ) {
            s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
            // #9682: remove data so that it's not used in an eventual retry
            delete s.data;
        }
    
    0 讨论(0)
  • 2020-12-14 16:22

    I think you should use JSON.stringify for GET parameters in URL like this:

    $.ajax({
               url: "/api/endpoint?parameters="+JSON.stringify({"sort":"date"}),
               type: "GET",
               contentType: "application/json",
               dataType: "json",
               ...
    
    0 讨论(0)
提交回复
热议问题