简体   繁体   English

jQuery,Javascript,AJAX POST json到api

[英]JQuery, Javascript, AJAX POST json to rest api

I have a problem with posting data to a REST API, it should be done like this: 我在将数据发布到REST API时遇到问题,应按以下方式完成:

curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" \
 -d '{"event":{"title":"event", "description": "nice", "start": "2018-03-11T22:00:00.000Z"}}' \
 http://events.restdesc.org/events

I have the following code: 我有以下代码:

function eventedit(request){
    console.log(request);
    var title = $("#title").val();
    var desc = $("#desc").val();
    var start = $("#start").val();
    start += ".000Z";
    $.ajax({
        url: request,
        type: "POST",
        dataType:'json',
        success: function (response) {
            console.log(response);
        },
        error: function(error){
            console.log("Something went wrong", error);
        }
    });
}

Like you see, I need to add data in my ajax request, but I don't know how to do it, do I need to make a string containing those values? 如您所见,我需要在ajax请求中添加数据,但是我不知道该怎么做,是否需要制作一个包含这些值的字符串? Or an array? 还是数组?

In your $.ajax call add data . $.ajax调用中添加data

 $.ajax({
    url: request,
    type: "POST",
    data: {"event":{"title": title, "description": desc, "start": start}},
    dataType:'json',
    success: function (response) {
        console.log(response);
    },
    error: function(error){
        console.log("Something went wrong", error);
    }
});

for POST you can also use a shorthand $.post 对于POST您还可以使用简写$.post

  $.post(request, {"event":{"title": title, "description": desc, "start": start}}, function(data){
    console.log(data);
});

Just use it like this if you're making a POST 如果要进行POST,请像这样使用它

$.post(request, {title: title, description: desc, start: start}, function (data) {
    console.log(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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