简体   繁体   中英

Using HTTP POST to query an API

I'm working with a lighting system which has an API that allows me to activate a 'Scene' via an HTTP POST request.

I can get it to work using the [ https://apigee.com/console/others ] API Tester by entering the URL, UN & PW, and the query into the body.

My question is - How do I structure this to embed it into a button in a webpage? Can I combine the URL and XML content from the body into a single URL string or would I need to call a separate XML file?

If so can anyone give me an example of the HTTP POST request to call an XML file?

I'm sure this is pretty basic stuff but I'm struggling to find the information amongst any of the tutorials I've found so far.

Robin

If the API is a true REST API, then it should support JSON as well, which are plain JavaScript objects - the jQuery library makes sending HTTP requests with AJAX really simple.

There's a gotcha though - for the browser to accept a POST request to a different domain than the one the webpage is being loaded from, the API will need to set a HTTP header to allow CORS . Either that, or the API must return a valid JSONP response, which implies that the API is called using GET rather than POST.

Here's an example jsFiddle to get you started.

$("button").click(function() {
    data = {
        param1:"FirstParamForServer",
        param2:"SecondParamForServer"
    };
    $.post("/echo/json/",data,function(result){
        console.log("Server has reponded successfully!");
        console.log(result);
        $("#result").html("Done!");
    })
});

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