将用户ID传递给core-ajax方法的GET请求,以从Google Cloud存储中检索数据。

huangapple go评论101阅读模式
英文:

Pass user ID to core-ajax method GET to retrieve data in Google Cloud storage

问题

我有一个在Google引擎上使用Go后端的应用程序。我正在尝试检索之前保存在Google云存储中的JSON文件。后端基于Polymer和JavaScript。问题是需要使用用户ID通过core-ajax调用来检索数据。

以下是我目前正在使用的JavaScript代码:

loadTrials: function loadTrials() {
    var _this = this,
        load = this.shadowRoot.querySelector('#load-trial');

    load.url = "http://url/loadTrials";
    load.go();
    load.addEventListener('core-response', function(ev) {
        var json = ev.detail.response;
        _this.trialData = JSON.parse(json)['trial-data'];
        console.log(JSON.parse(json)['trial-data'])
    }, false);
}

HTML部分:

<core-ajax id="load-trial" method="GET"></core-ajax>

Go后端代码(只包含相关部分):

func handleloadTrials(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()

    //retrieve trials
    http.ServeFile(w, r, 与用户ID相关的JSON文件)
}

我知道这段代码是错误的,但我完全被困住了,不知道如何将用户ID传递给GET方法,然后使用该ID从云存储中检索特定的文件(它是一个JSON文件),然后将此JSON文件传递给Go中的http.ServeFile方法。

需要帮助吗?非常感谢。

英文:

I have an app in google engine with a go backend. I'm trying to retrieve a json file that I previously saved in google cloud storage. The backend is based on polymer and javascript. The problem is that the data need to be retrieved using the user-id through a core-ajax call.

Here is the javascript code I'm using at the moment:

loadTrials : function loadTrials() {
            var _this = this,
                load = this.shadowRoot.querySelector(&#39;#load-trial&#39;);

            load.url=&quot;http://url/loadTrials&quot;;
            load.go();
            load.addEventListener(&#39;core-response&#39;, function(ev) {
                var json = ev.detail.response;
                _this.trialData = JSON.parse(json)[&#39;trial-data&#39;];
                console.log(JSON.parse(json)[&#39;trial-data&#39;])
            }, false);
        }

The HTML

&lt;core-ajax id=&quot;load-trial&quot;  method=&quot;GET&quot;&gt;&lt;/core-ajax&gt;

And the backend in go(just the relevant part):

func handleloadTrials(w http.ResponseWriter, r *http.Request) {
	
	defer r.Body.Close()

	//retrieve trials
    http.ServeFile(w, r, JSON file related to user id)

}

I know this code is wrong, but I'm completely stuck and I don't know how to pass the user ID to the GET method, and then use the ID to retrieve the specific file on cloud storage (it's a json file) and then pass this Json file to the http.ServeFile method in Go.

Any help?
Thanks a lot.

答案1

得分: 1

<core-ajax url="{{url}}" handleAs="json" params='{"userID": "{{userID}}"}'></core-ajax>

参数应该是 JSON 格式的。

英文:
&lt;core-ajax url=&quot;{{url}}&quot; handleAs=&quot;json&quot; params=&#39;{&quot;userID&quot;: &quot;{{userID}}&quot;}&#39;&gt;&lt;/core-ajax&gt;

The parameter should be on JSON format.

答案2

得分: 0

我以这种方式部分解决了问题

Javascript:

loadTrials : function loadTrials() {
            var _this = this,
                load = this.shadowRoot.querySelector('#load-trial');
            //将userID传递给core-ajax
            _this.userID = _this.app.userSession.user;
            load.url="http://url/loadTrials";
            load.go();
            load.addEventListener('core-response', function(ev) {
                var json = ev.detail.response;
                _this.trialData = JSON.parse(json)['trial-data'];
                console.log(JSON.parse(json)['trial-data'])
            }, false);
        }

HTML:

<core-ajax id="load-trial" params="{{userID}}" method="GET"></core-ajax>

Go:

type trialStruct []struct {
	Trial struct {
		Index           int    `json:"index"`
		Word            string `json:"word"`
		WordDisplayTime int    `json:"wordDisplayTime"`
		AnswerMaxTime   int    `json:"answerMaxTime"`
		FixationTime    int    `json:"fixationTime"`
		Train           bool   `json:"train"`
		Test            bool   `json:"test"`
		Grammatical     bool   `json:"grammatical"`
		Grammar         string `json:"grammar"`
		keyboard        bool   `json:"keyboard"`
	}
	Metadata struct {
	}
}

func (d *saveData) readFile(fileName string) trialStruct {
	trialName := fileName + "/trials"
	rc, err := storage.NewReader(d.ctx, bucket, trialName)
	if err != nil {
		d.errorf("readFile: unable to open file from bucket %q, file %q: %v", bucket, trialName, err)

	}
	defer rc.Close()
	slurp, err := ioutil.ReadAll(rc)
	if err != nil {
		d.errorf("readFile: unable to read data from bucket %q, file %q: %v", bucket, fileName, err)
	}
	var trialJson trialStruct
	err1 := json.Unmarshal(slurp, &trialJson)
	if err != nil {
		log.Printf("error:", err1)
	}
	return trialJson
}

但现在我有一个编码的Json文件,我不确定如何将其发送回Javascript,需要帮助吗?谢谢

英文:

I partially solved in this way

Javascript:

loadTrials : function loadTrials() {
            var _this = this,
                load = this.shadowRoot.querySelector(&#39;#load-trial&#39;);
            //pass userID to core-ajax
            _this.userID = _this.app.userSession.user;
            load.url=&quot;http://url/loadTrials&quot;;
            load.go();
            load.addEventListener(&#39;core-response&#39;, function(ev) {
                var json = ev.detail.response;
                _this.trialData = JSON.parse(json)[&#39;trial-data&#39;];
                console.log(JSON.parse(json)[&#39;trial-data&#39;])
            }, false);
        }

HTML:

&lt;core-ajax id=&quot;load-trial&quot; params=&quot;{{userID}}&quot; method=&quot;GET&quot;&gt;&lt;/core-ajax&gt;

Go:

type trialStruct []struct {
	Trial struct {
		Index           int    `json:&quot;index&quot;`
		Word            string `json:&quot;word&quot;`
		WordDisplayTime int    `json:&quot;wordDisplayTime&quot;`
		AnswerMaxTime   int    `json:&quot;answerMaxTime&quot;`
		FixationTime    int    `json:&quot;fixationTime&quot;`
		Train           bool   `json:&quot;train&quot;`
		Test            bool   `json:&quot;test&quot;`
		Grammatical     bool   `json:&quot;grammatical&quot;`
		Grammar         string `json:&quot;grammar&quot;`
		keyboard        bool   `json:&quot;keyboard&quot;`
	}
	Metadata struct {
	}
}

func (d *saveData) readFile(fileName string) trialStruct {
	trialName := fileName + &quot;/trials&quot;
	rc, err := storage.NewReader(d.ctx, bucket, trialName)
	if err != nil {
		d.errorf(&quot;readFile: unable to open file from bucket %q, file %q: %v&quot;, bucket, trialName, err)

	}
	defer rc.Close()
	slurp, err := ioutil.ReadAll(rc)
	if err != nil {
		d.errorf(&quot;readFile: unable to read data from bucket %q, file %q: %v&quot;, bucket, fileName, err)
	}
	var trialJson trialStruct
	err1 := json.Unmarshal(slurp, &amp;trialJson)
	if err != nil {
		log.Printf(&quot;error:&quot;, err1)
	}
	return trialJson
}

But now I have the Encoded Json file which I'm not sure how to send back to the javascript, any help? Thanks

huangapple
  • 本文由 发表于 2015年5月19日 03:56:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/30311770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定