以前,我可以使用ajax
将数据从HTML表单发送到Google表单(回复电子表格)。这是代码。
Ajax代码
function postContactToGoogle() {
var email = $('#emailtosubscribe').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/[key]/formResponse",
data: {
"entry_1064445353": email
},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
window.location.reload();
},
200: function() {
window.location.reload();
}
}
});
}
现在,我正在尝试使用UnityWebRequest
在Unity中执行相同操作。这是我的代码
Unity代码
public class SendToGoogle : MonoBehaviour {
public GameObject email;
private string Email;
[SerializeField]
private string BASE_URL = "https://docs.google.com/forms/d/e/[key]/formResponse";
IEnumerator Post(string json) {
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(json);
using (UnityWebRequest www = new UnityWebRequest(BASE_URL, UnityWebRequest.kHttpVerbPOST)) {
UploadHandlerRaw uH = new UploadHandlerRaw(bytes);
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
www.uploadHandler = uH;
www.downloadHandler = dH;
www.SetRequestHeader("Content-Type", "application/json");
yield return www.Send();
if (www.isError) {
Debug.Log(www.error);
} else {
Debug.Log(www.ToString());
Debug.Log(www.downloadHandler.text);
}
}
}
public void Subscribe() {
Email = email.GetComponent<InputField>().text;
var n = new JSONObject();
n["entry_1064445353"] = Email;
string json = n.ToString();
Debug.Log(Email);
StartCoroutine(Post(json));
}
}
现在,当我尝试从场景提交电子邮件时,会在电子表格中创建时间戳,但不会保存电子邮件。我对www.SetRequestHeader("Content-Type", "application/json");
感到怀疑,就像我ajax
使用xml
datatype
和dataType: "xml"
一样。
此外,我还尝试仅发送string
而不将其更改为JSONObject
,并将Content-Type
上的SetRequestHeader
更改为xml
。
答案 0 :(得分:4)
最后,我使用WWW
和WWWForm
找出了它,并设法创建视频教程,因为我很难为如何将数据保存到Google电子表格中获得解决方案统一
视频教程:How to save data to Google Spreadsheet from Unity(YouTube)
这是我必须更改的代码段。
IEnumerator Post(string email) {
WWWForm form = new WWWForm();
form.AddField("entry.1064445353", email);
byte[] rawData = form.data;
string url = BASE_URL;
// Post a request to an URL with our custom headers
WWW www = new WWW(url, rawData);
yield return www;
}
public void Subscribe() {
Email = email.GetComponent<InputField>().text;
StartCoroutine(Post(Email));
}