2017-05-26 299 views
2

以前,我能夠使用ajax將數據從HTML表單發送到Google表單(回覆電子表格)。這是代碼。如何使用Unity 3D將數據保存到Google SpreadSheet中

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做同樣的統一。這裏是我的代碼

統一編碼

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作爲datatypedataType: "xml"

而且,我也試過只發送string,而不將其更改爲JSONObjectSetRequestHeader改變Content-Typexml

+0

但是你的Ajax代碼是用xml發送的,而且unity正在發送的是用json發送的。兩者都不是 - 你確定另一端可以處理json嗎? – Programmer

+0

另一端是谷歌窗體,我用來創建該腳本的引用4個月前,我發現數據類型應該是'xml',現在我想從統一發送數據爲'xml'。這是可能的,無法在UnityWebRequest SetRequestHeader的內容類型上找到好的文檔。 –

+0

另外,混淆了Google表單接受的'xml'結構。 –

回答

3

最後,我想通了使用WWWWWWForm,也成功地創建一個視頻教程,因爲這是我很難獲得解決方案如何將數據向谷歌電子表格從Unity

視頻教程保存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)); 
} 
+0

不錯。你甚至不需要xml – Programmer

+0

是的,謝謝你在那裏,你總是激勵我。 –

+1

不客氣。這個問題讓我想起[This](https://stackoverflow.com/a/43823046/3785314)帖子,它無法與UnityWebRequest一起使用,但是可以使用WWW和WWWForm的形式。 – Programmer

相關問題