2016-06-10 71 views
0

我正在嘗試使用Google Apps腳本訪問POST請求的參數。我可以使用e.parameter記錄params對象,儘管我似乎無法通過使用e.parameter.name來訪問對象的鍵。訪問XMLHttpRequest中的參數Google Apps腳本

的XMLHttpRequest

var http = new XMLHttpRequest(); 
    var url = "myappURL"; 
    var params = JSON.stringify({employeeStatus: "Active", name: "Henry"}); 

    http.open("POST", url, true); 

    //Send the proper header information along with the request 
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

    //Call a function when the state changes. 
    http.onreadystatechange = function() { 
    // call back function 
    } // end callback 

    http.send(params); 

谷歌Apps腳本

function doPost(e) { 
    if (typeof e !== 'undefined') { 
    Logger.log(e.parameter.name); // does not work (undefined) 
    } // end if 
} // end doPost 
+0

也許你可以分享一個公共版本的腳本來看看嗎? – Sudsy

+0

@Sudsy [link](https://script.google.com/d/1MxBNwUoG4I_F0Gt1GGYzNrr3m6PakhcDFxIA_g-nvoS-bRHx0IS5jgMJ/edit?usp=sharing) –

回答

0

有數據是通過HTTP所帶來的不同的方式微妙的怪癖。例如,我注意到當json數據的常用標題是Content-Type:application/json時,您正在使用Content-type「application/x-www-form-urlencoded」。

我添加了一行,它只是返回e變量的內容,因此您可以看到返回的內容。

我用curl用下面的命令進行調試。

curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec 

我收到的反應是:

{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}} 

你可以看到,在我的情況下,JSON在內容領域,而不是參數返回。

你可以試着用腳本來看看你得到了什麼。您也可以嘗試更改內容類型。

經過進一步測試,我認爲你最好提交一個表單數據而不是json。我已經能夠通過修改您的javascript返回paramer:

var http = new XMLHttpRequest(); 
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec"; 
var params = "employeeStatus='Active'&name='Henry'"; 

http.open("POST", url, true); 

//Send the proper header information along with the request 
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

//Call a function when the state changes. 
http.onreadystatechange = function() { 
    if (http.readyState==4) { 
    //alert the user that a response now exists in the responseTest property. 
    console.log(http.responseText); 
    // And to view in firebug 
    // console.log('xhr',xmlhttp) 
    } 
} // end callback 

http.send(params); 
+0

當記錄e變量的內容時,這是結果 '{parameter = {{ 「employeeStatus」:「Active」,「name」:「Henry」} =},contextPath =,contentLength = 42,queryString = null,parameters = {{「employeeStatus」:「Active」,「name」:「Henry」} = [Ljava.lang.Object; @ 68bdf26b},postData = FileUpload}' –

+0

請參閱編輯答案 – Sudsy

+0

中的完整解決方案。你的答案很棒! –