简体   繁体   中英

How do I POST JSON data using jQuery AJAX

I've recently been given a project, the instructions are as follows:

Create an HTML page that will make a call to our API endpoint to retrieve a list of logs on our API logger, load the data into a visually pleasing grid. The page should make this call every minute, and up existing rows with new data via AJAX (partial page update, the entire page should not reload). If the row no longer exist in the new data, remove the row. If new data does not exist in any of the rows, add a new row with the data.

The API call is to be made using the POST method with jQuery AJAX snippets to our API endpoint, with the following JSON Request object:

 { "token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO" }

The JSON Response object from the server should look something like this:

 { "logs": [ { "Description": string, "ApplicationName": string, "Client_IP": string, "Server_IP": string, "RequestEndPoint": string, "LastOccurrence": datetime string, "ResponseCode": integer, "Last24HourLogCount": integer }, ] }

I'm having trouble with the POST request and gathering the JSON data. When I make an API test call using Postman I'm able to receive the JSON data, but not when I make the calls through my HTML page, below are my attempts:

Attempt 1

Here I created a POST request to the endpoint and attempt to convert the JSON data into a string to be displayed within an alert:

I got the following alert popup:

This is the message in the console:

If I remove the token header and add the JSON data from Postman to my variable I get this console error instead:

$.ajax({
    type: "POST",
    url: "https://fetch1.hipposhq.com/hipposapilogstatus",
    data: data,
    dataType: 'json',
    headers:{
         "token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO"
    },
    success: function(data){alert(JSON.stringify(data))},
    error: function(errMsg) {
         alert(errMsg);
    }
});

Attempt 2

Here I created a POST request to the endpoint and attempt to display the JSON data in the console log, I receive an error instead:

This is the message in the console:

If I remove the token header and add the JSON data from Postman to my variable I get the same error:

var data = {}

$.ajax({
    type: "POST",
    url: "https://fetch1.hipposhq.com/hipposapilogstatus",
    data: data,
    dataType: 'json',
    headers:{
        "token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO"
    },             
    success: function(data){
        console.log(data);
    }
});

Attempt 3

Here I created a POST request with the JSON data I received from Postman (actual data omitted) to receive the JSON data and display it in the console log, I receive an error instead:

This is the error in the console:

When I add the token header I receive the same access and resource errors:

$.ajax({
    type:"POST",
    url:"https://fetch1.hipposhq.com/hipposapilogstatus",
    processData: false,
    dataType: 'json',
    data: JSON.stringify({
            "logs": [
                {
                "Description": "string",
                "ApplicationName": "string",
                "Client_IP": "string",
                "Server_IP": "string",
                "RequestEndPoint": "string",
                "LastOccurrence": "datetime string",
                "ResponseCode": integer,
                "Last24HourLogCount": integer,
                },
            ]
        }),
    success: function(data){
        console.log(data);
    }
});

I want to be able to receive the JSON data in the console as a string/object/array so I can display it on my page, but I'm unsure of where to go from here.

You had to send the token as data

 const $output = $("#logs"); const process = response => $output.html( response.logs.map(log => `<hr/><dl>${ Object.entries(log).map(([key,val]) => `<dt>${key}</dt><dd>${val}</dd>`).join("") }</dl>`).join("")); $.ajax({ type: "POST", url: "https://fetch1.hipposhq.com/hipposapilogstatus", dataType: 'json', data: { "token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO" }, success: process, error: function(request, status, error) { console.log(request.responseText); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="logs"><div>

 var data = { "logs": [{ "Description": 'string', "ApplicationName": 'string', "Client_IP": 'string', "Server_IP": 'string', "RequestEndPoint": 'string', "LastOccurrence": 'datetime string', "ResponseCode": 'integer', "Last24HourLogCount": 'integer' }, ] } $.ajax({ type: "POST", url: "https://fetch1.hipposhq.com/hipposapilogstatus", data: data, dataType: 'JSON', headers: { "token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO" }, success: function(data) { console.log(data); }, });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM