How do I work with JSON as ajax response?

0 favourites
  • 6 posts
  • I have found a couple topics, but it's so damn confusing.

    Here is what i am trying to do.

    I am calling my rails server with an ajax request to save scores in a game, and returns an ajax response which i would like to update either a dom element or just some webstorage with responses.

    I am able to store the json string response in a webstorage currently..but to extract individual json data values from that is where I lose it. Is there a good tutorial on this? I have been digging for a few days, and am so confused.

    Thanks!

  • Why not manipulate the data before storing it as json ?

    Your Ajax responses would simply update the object with the values, then store it as json

  • Not sure I understand.

    Once the object is updated with the values returned from ajax, which is a JSON string, there's an easy way to extract the pieces to use before I store it?

    Example ajax response: {"score":"5","high_score":"315","game_token":"xyzabc"}

    How would I be able to extract each piece of that before storing it?

    I am not even able to find a good tutorial on how to extract after storing to a json either...which would probably help.

  • You need to use a C2 format.

    {"c2dictionary":true,"data":{"score":"5","high_score":"315","game_token":"xyzabc"}}

    Load this JSON to dictionary, and you will be able to read any data very easily: "myDictionay.Get("score")", etc.

    Your rails server should take care of that output format, this will make your life easier. For example my PHP server C2 core API contains following functions:

    protected function outputAsC2DictionaryJSON($data)
    	{
    		$data = array(
    			'c2dictionary' => true,
    			'data' => $data
    		);
    		$this->outputData($data);
    	}
    	
    	protected function outputAsC2ArrayJSON($data, $arrayDimensions)
    	{
    		$data = array(
    			'c2array' => true,
    			'size' => $arrayDimensions,
    			'data' => $data
    		);
    		$this->outputData($data);
    	}
    	
    	private function outputData($data)
    	{
    		header('Content-Type: application/json');
    		echo json_encode($data);
    		exit(1);
    	}[/code:1jdk7h4w]
  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Thank you so much! This appears to be working as I need!

  • Hi ,

    I am calling below mentioned function in browser object. How to read the "resp" of this function in construct 2.

    If any one is having answer of this question please help.

    Browser.ExecJS("parent.saveGameScore ? parent.saveGameScore(" & lastscore & ", function (resp) {

    }) : console.log(122)")

    Thanks

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)