2

I currently have a website using PHP (Laravel) on the server and Javascript in the client. Now I'd like to replace the Javascript with Dart.

On the current webpage, I inject some data into the Javascript like this:

<script>
    var mydata = <?php echo $mydata; ?>;
    /* now do something with mydata */
</script>

My question is: how do I rewrite this to Dart?

My first take would be:

<script type="application/dart">
    main() {  
        var mydata = <?php echo $mydata; ?>
        /* now do something with mydata */
    }  
</script>

But this approach makes it impossible to generate Javascript code with dart2js since there is dynamically generated code included in the Dart code.

I can of course use an Ajax request, but I choose to place the generated data in the Javascript code because that makes one less HTTP request, making the webpage load faster.

So how would I go about injecting PHP generated data into Dart, without using a HTTP request while still being able to use dart2js?

2
  • 1
    Another to improve loading time is to add a prefetch tag for your json data: <link rel="subresource" href="data.json"> Then when you make the the ajax request the data will likely already have been downloaded. Commented Dec 23, 2013 at 21:45
  • That's interesting Greg, I didn't one can do that. It would still be an extra HTTP request and I want to use the data right away on load, so in my case I don't see it as a solution. Commented Dec 24, 2013 at 7:25

2 Answers 2

2

The simplest solution is to generate datas in JS like you already do and read them from Dart with dart:js. Thus you will have to compile with dart2js only one time.

In your file.php :

<script>
    var myDatasAsJsonString = "<?php echo $myDatasAsJsonString; ?>";
</script>

In your Dart file :

import 'dart:js' as js;
import 'dart:convert' show JSON;

main() {
  final myDatasAsJsonString = js.context['myDatasAsJsonString'];
  final myDatasAsJson = JSON.decode(myDatasAsJsonString);
  /* now do something with mydata */
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! That looks like a workable solution. I'll try that as soon as I'm back home from work. A 'pure' Dart solution might be more elegant but this will certainly work for me.
2

Another solution to my own question is this:

<script type="application/json" id="json-data">
    <?php echo json_encode($myData); ?>
</script>

and import this in Dart like:

void main() {
    var myData = JSON.decode(querySelector('#json-data').text);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.