jQuery发布JSON

hs1ihplo  于 2023-08-04  发布在  jQuery
关注(0)|答案(4)|浏览(114)

update:我想把var value传给服务器。
你好,老样子,老样子...:)
我有一个名为<form id="testForm" action="javascript:test()">的窗体和一个名为<code id="testArea"></code>的代码区
我正在使用以下代码字符串化并显示代码区域中的数据:

var formData = form2object('testForm');
document.getElementById('testArea').innerHTML = JSON.stringify(formData, null, '\t');
var value = JSON.stringify(formData, null, '\t');

字符串
我想要的是将这些数据发送到JSON文件。我一直在做这个项目:http://ridegrab.com/profile_old/,如果您按下Submit Query按钮,您将看到填充得页面标题.
我还想用这段脚本来发送数据:

function authenticate(userName, password) {
    $.ajax
    ({
        type: "POST",
        //the url where you want to sent the userName and password to
        url: 'username:password@link to the server/update',
        dataType: 'json',
        async: false,
        //json object to sent to the authentication url
        data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
        success: function () {

        alert("Thanks!"); 
        }
    })
}


同样,我所希望的只是能够将JSON数据发送到服务器。我的服务器被设置为update or POST数据在正确的地方。

nbewdwxp

nbewdwxp1#

'data'应该是字符串化的JavaScript对象:

data: JSON.stringify({ "userName": userName, "password" : password })

字符串
要发送formData,请将其传递给stringify

data: JSON.stringify(formData)


某些服务器还需要application/json内容类型头:

contentType: 'application/json'


这里还有一个类似问题的更详细的答案:Jquery Ajax Posting JSON to webservice

d5vmydt9

d5vmydt92#

如果您将此帖子请求发送到跨域,请查看此链接。
https://stackoverflow.com/a/1320708/969984
您的服务器不接受跨站点发布请求。因此,需要更改服务器配置以允许跨站点请求。

x8goxv8g

x8goxv8g3#

Post async function with event.

//---------------------Buffers <0-9>--------------------- 
var gBuffer=[];

function GetBuffer(pIndex=0) {
    if (pIndex<0 || pIndex>9) {
        console.log('Error, pIndex out of interval <0,9>');
        return null;
    }
    if (gBuffer.length<10) {gBuffer.length=10;}
    return gBuffer[pIndex];
}

function SetBuffer(pIndex=0, pJson="") {
    if (pIndex>=10 || pIndex<0) { 
        console.log('Error, pIndex out of interval <0,9>');
        return null;
    } 
    if (gBuffer.length<10) {gBuffer.length=10;}
    return gBuffer[pIndex]=pJson;
}

//---------------------Post and generate event--------------------- 

function sleep(ms=3) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function gWait(pIndex=0, pTimeoutSec=10, pEventTag="html", pEventName="PostEvent" ) {  // async, generate event 
    if (pIndex<0 || pIndex>9) {
        console.log('Error, pIndex out of interval <0,9>');
        return;
    }
    var i=0;
    console.log('gWait start');
    while (i < 25*pTimeoutSec && GetBuffer(pIndex)==null) {
      await sleep(40);
      i++;
    }
    if (i>=25*pTimeoutSec)  {
      SetBuffer(pIndex,'{"error":"SRV error. Fetch timeout ('+pTimeoutSec+' sec)"}');
    }
    console.log('gWait stop, iteration:'+i+'/'+25*pTimeoutSec);
    $(pEventTag).trigger(pEventName,pIndex); //generate event
}

async function Post(pJSON="", pIndex=0, pTimeoutSec=10, pEventTag="html", pEventName="PostEvent") { //send JSON and return response to gArray[pIndex]
    if (pIndex<0 || pIndex>9) {
        console.log('Error, pIndex out of interval <0,9>');
        return;
    }
    var js=Trim(pJSON);
    if (js=="") { js="{}"; } //empty JSON   
    SetBuffer(pIndex,null);
    try {
        if (pTimeoutSec>0) {gWait(pIndex,pTimeoutSec,pEventTag,pEventName);} //timeout controll, and generate event
        var resp=await fetch("ajax",   //url to server example: "http://localhost:8081/api/services/tags/"
        {   method: "POST",
            headers: {"Content-Type": "application/json; charset=utf-8" },
            body: js,
            async: true,
        })
        if (resp.status==200) {
            const result= await resp.json();
            SetBuffer(pIndex,JSON.stringify(result));
        } else {
            SetBuffer(pIndex,'{"error":"SRV error. '+resp.status+'"}');   
        }
    }
    catch (err) {
       SetBuffer(pIndex,'{"error":"SRV error. Failed to fetch."}');
    }  
    if (pTimeoutSec<=0) { $(pEventTag).trigger(pEventName,pIndex);} //generate event
}

$(document).ready(function(){
   alert('ok');
   $("html").on("PostEvent", function(event,msg){ 
      console.log(event.type+' gBuffer['+msg+']:'+GetBuffer(msg));
   });
   
   $("form").submit(function (event) {
       event.preventDefault();
       Post('{"hello":""}');  //JSON post
       event.preventDefault();
    });
});

字符串

ccgok5k5

ccgok5k54#

你这样发布JSON

$.ajax(url, {
    data : JSON.stringify(myJSObject),
    contentType : 'application/json',
    type : 'POST',
    ...

字符串
如果你以www.example.com的形式传递一个对象settings.datajQuery会将其转换为查询参数,并默认使用数据类型application/x-www-form-urlencoded发送; charset=UTF-8,可能不是你想要的

相关问题