I am creating the below url request which launches a flex application through the mentioned url. I have also added data and set url req method to POST. How can I read this POST data in my Flex Application which is being launched
var urlReq:URLRequest = new URLRequest();
var requestVars:URLVariables = new URLVariables();
requestVars.id = 'abc';
urlReq.data = requestVars;
urlReq.method = URLRequestMethod.POST;
urlReq.url = '../../bin-debug/FlexApp.html';
navigateToURL(urlReq);
Could you pass your variables within the url and then use flashvars via swfobject to pass them to the target app?
I've had more or less similar issue, and used this method.
In my first swf:
var urlReq:URLRequest = new URLRequest(String("game.html?user_id="+userId+"&user_code="+userCode));
And then in game.html I parsed those variables and sent then as flashvars:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
};
var flashvars = {
user_id: getUrlVars()["user_id"],
user_code: getUrlVars()["user_code"]
};
var params = {
quality: "high",
bgcolor: "#000000",
play: "true",
loop: "true",
wmode: "window",
scale: "showall",
menu: "true",
devicefont: "false",
allowScriptAccess: "true"
};
swfobject.embedSWF("preloader.swf", "flashContent", "980", "663", "11.2.0",false, flashvars, params);
</script>
And finally in my target swf I received them like this:
var userId:String = loaderInfo.parameters.user_id as String;
var userCode:String = loaderInfo.parameters.user_code as String;
I hope this helps, and if not, then I probably didn't understand the main issue.
The POST data is sent to the server, so if you want to read it on FlexApp.html from the client then the server needs to echo it back on that page somehow. Otherwise you could use a GET request and access the request parameters using JavaScript window.location.search.
Here's an example using PHP to output the POST variables as JSON to the page:
<script>
var post_params = <? echo json_encode($_POST); ?>
function getPostParam(name){
return post_params[name];
}
</script>
Call from JavaScript:
alert(getPostParam("id"));
Call from ActionScript:
trace(ExternalInterface.call("getPostParam", "id"));
Related
I have an object I wold like to pass to a templated HTML file. If I use a simple variable, all is fine, as these work:
on the server side I have the following at the top of code.gs:
//Define this here globally so it is accessed in the HTML Template
var passedFestival = ' ';
var passedSID = ' ';
var passedRID = 'FALSE';
in the HTML file I have:
<script>
var passedFestival = '<?!= passedFestival ?>';
var passedSID = '<?!= passedSID ?>';
var passedRID = '<?!= passedRID ?>';
</script>
I can use these in later code and get the appropriate value. I want to also use an Object, which is the result of reading a couple rows from the spreadsheet, and basically results in the following outside any function, same as the other variables, above:
var testformOptions = [];
testformOptions['currencies'] = [{"currency":"CAD", "default":false, "defaultOption":"Interac", "paymentOptions":"Cheque|Credit Card|Interac|PayPal", "sheetrow":2}, {"currency":"USD", "default":true, "defaultOption":"PopMoney", "paymentOptions":"Cheque|Credit Card|PayPal|PopMoney", "sheetrow":3}];
testformOptions['meals'] = {"use":true, "required":false, "default":"Omnivore", "values":"Omnivore|Vegan"};
in the HTML file I can reference the object's individual values:
if ('<?!= testformOptions.currencyOptions.use ?>') {
$("#currencies").show();
}
But I would rather copy the object over completely and reference it as part of the client side data. I have tried a few things, most of which I understand why they didn't work, but I thought this would:
var formOptions = jQuery.extend(true, {}, <?!= testformOptions?>;
I have tried saving the data to a variable as json, but that didn't work since I have single quotes and other special characters in my final object.
Is there any way to get an object passed into an object on the client side outside using google.script.run to pass it after loading? I am reading the spreadsheet data as part of the initial doGet so I figured it may be faster to use templated HTML and pass the object.
EDIT
Thanks to the reply, I have working code. The final sample reads as follows. Some items are left out to allow focusing on the important parts.
Code.gs:
var passedSID = ' ';
var passedRID = 'FALSE';
function doGet(passed) {
if(passed.parameter.rid && passed.parameter.msid){
// A registration ID and Spreadsheet ID were passed so this is to edit an existing registration
passedSID = passed.parameter.msid;
passedRID = passed.parameter.rid;
var registrationValues = getRegistrationValues(passedSID, passedRID);
}
else if(passed.parameter.msid){
// A Spreadsheet ID was passed so this is to complete a new registration
passedSID = passed.parameter.msid;
}
//get the form options from the appropriate spreadsheet file
//getFormOptions() is from Tutorial: Simple Mail Merge
//https://developers.google.com/apps-script/articles/mail_merge
testformOptions = getFormOptions(passedSID);
//Create the HTML template
var template = HtmlService.createTemplateFromFile('Index');
template.data = JSON.stringify(testformOptions);
// Build and return HTML in IFRAME sandbox mode.
return template.evaluate()
.setTitle('Registration Form').setWidth(620).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function include(filename) {
return HtmlService.createTemplateFromFile(filename).evaluate()
.getContent();
}
Index.html:
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<link href="https://fonts.googleapis.com/css?family=Raleway:100" rel="stylesheet">
<html>
<body>
<div id="mybody">
<form>
<!-- Boring form html -->
</form>
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var formOptions = $.extend(true, {}, <?!= data ?>);
</script>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('jquery_cloneform_js').getContent(); ?>
<?!= include('JavaScript'); ?>
And in JavaScript.html:
<script>
var passedSID = '<?!= passedSID ?>';
var passedRID = '<?!= passedRID ?>';
// use onload to call initialization after the document loads
window.onload = setForm;
function setForm(){
var optionArray = [];
var defaultOption = '';
if (formOptions.currencyOptions.use) {
$("#currencies").show();
//Set the options for the currency
var options = formOptions.currencyOptions.values;
defaultOption = formOptions.currencyOptions.defaultOption;
optionArray = options.split("|");
setSelectOptions('regcurrency', optionArray, defaultOption);
var options = formOptions.currencies[1].paymentOptions;
defaultOption = formOptions.currencies[1].defaultOption;
optionArray = options.split("|");
setSelectOptions('paymentMethod', optionArray, defaultOption);
}
}
How about a following answer?
Modification points :
var testformOptions = [];
testformOptions['currencies'] = [{"currency":"CAD", "default":false, "defaultOption":"Interac", "paymentOptions":"Cheque|Credit Card|Interac|PayPal", "sheetrow":2}, {"currency":"USD", "default":true, "defaultOption":"PopMoney", "paymentOptions":"Cheque|Credit Card|PayPal|PopMoney", "sheetrow":3}];
testformOptions['meals'] = {"use":true, "required":false, "default":"Omnivore", "values":"Omnivore|Vegan"};
About the above script, testformOptions is defined as an array. So testformOptions['currencies'] and testformOptions['meals'] cannot be imported. So please modify from var testformOptions = []; to var testformOptions = {};.
When it passes the object, please use JSON.stringify().
The scripts reflected above modifications are as follows.
code.gs :
function doGet() {
var testformOptions = {};
testformOptions['currencies'] = [{"currency":"CAD", "default":false, "defaultOption":"Interac", "paymentOptions":"Cheque|Credit Card|Interac|PayPal", "sheetrow":2}, {"currency":"USD", "default":true, "defaultOption":"PopMoney", "paymentOptions":"Cheque|Credit Card|PayPal|PopMoney", "sheetrow":3}];
testformOptions['meals'] = {"use":true, "required":false, "default":"Omnivore", "values":"Omnivore|Vegan"};
var t = HtmlService.createTemplateFromFile('index');
t.data = JSON.stringify(testformOptions);
return t.evaluate();
}
index.html
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<p id="disp"></p>
<script>
var data = $.extend(true, {}, <?!= data ?>);
$('#disp').text(JSON.stringify(data));
</script>
Result :
{
"currencies": [
{
"currency": "CAD",
"default": false,
"defaultOption": "Interac",
"paymentOptions": "Cheque|Credit Card|Interac|PayPal",
"sheetrow": 2
},
{
"currency": "USD",
"default": true,
"defaultOption": "PopMoney",
"paymentOptions": "Cheque|Credit Card|PayPal|PopMoney",
"sheetrow": 3
}
],
"meals": {
"use": true,
"required": false,
"default": "Omnivore",
"values": "Omnivore|Vegan"
}
}
If I misunderstand your question, I'm sorry.
I am currently trying to figure out how I can retrieve a single value from a sap.ui.model.json.JSONModel
in my main view:
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
};
oController.getConfiguration(getConfigCallback);
console.log(gConfigModel);
in my controller:
getConfiguration : function(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
callback(config);
$.getJSON(sServiceUrl).done(function(data) {
config = data.d;
callback(config);
});
},
In my console.log statement I can see that the data was successfully passed from the backend and successfully set to the JSON model. My requirement is to store the value of attribute Editable in a single variable.
I already tried gConfigModel.getProperty('/'), didnt work. tried to access gConfigModel.oData was undefined .. How can I store it in a single value?
Solution Comment: If you catch data from a backend, you have to take care how long it takes. data can be available later then expected, in my case I added 1s timeout, afterwards I can access the property easily
setTimeout(function() {
console.log(gConfigModel.getProperty('/Editable'));
}, 1000);
I wouldn't advise using the model's getData() method since it is deprecated.
A much better solution is to use gConfigModel.getProperty("/Editable")
(I'm using the root slash here since your property resides in the root of your model)
In the same way, you can also set your data:
gConfigModel.setProperty("/Editable", <your new value>) instead
First of all, thanks for the effort to find solutions of our Problems! (at least, those regarding It stuff.. :) )
I've found a solution which I think is a little bit more save because the timeout is maybe somewhat arbitrary - it would depend on the machine or the amount of data that is to be fetched?
Therefore, I am using an attachRequestCompleted function:
with sUrl_2="path-to-my-service";
var oModel_2 = new sap.ui.model.json.JSONModel(sUrl_2);
oModel_2.attachRequestCompleted(function(data) {
//now, i can access the data stored in the oModel_2, either by getProperty, or by DOM: oModel_2.oData.d.Vendor
gv_selLieferant = oModel_2.getProperty("/d/Vendor");
gv_selEinkOrg = oModel_2.getProperty("/d/PurchOrg");
gv_selEinKGru = oModel_2.getProperty("/d/PurGroup");
});
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>
<script>
function getConfiguration(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
var data = {
"d": {
"_metadata": "",
"Backup01": "01",
"Editable": "True"
}
};
setTimeout((function() {
config = data;
callback(config);
})(), 2000);
};
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
alert(gConfigModel.getProperty("/d/Editable"));
};
getConfiguration(getConfigCallback);
</script>
I have embedded a single swf three times named as video.swf.
The swfs names are video1 , video2 and video3.
If I play a swf, I wants to get the currently playing swf's name?
Is it possible ?
I'm using javascript for communication.
I had to do something very similar for work on a project for Swatch/MTV (having multiple embedded players on a page and playing only one clip at a time (playing a different clip, would pause others, etc.)
e.g.
var vids = ['video/file/72066f40bfcaea46e10460585b4e4bcb.mp4','video/file/3d5db6b87f9cdacb016c9c55afed1e08.mp4','video/file/c18b04a1a548cbf20609de70a106d7cc.mp4','video/file/4568a11f3f6a7ff467a85fefe2ac08e6.mp4','video/file/b91081d37a81692194c0e34580958c51.mp4']; for(var i = 0 ; i < vids.length; i++){
var flashvars = {};
flashvars.video_url = 'http://www.swatchmtvplayground.com/'+vids[i];
flashvars.video_id = i;
flashvars.locale = "gb";
flashvars.skin = 'upperBackground:0xf8c3c4,lowerBackground:0xe2e2e2,generalControls:0x000000,slider:0xb58f8f,progress:0xe2e2e2';
var params = {};
var attributes = {};
attributes.id = "mediaplayer"+i;
so = swfobject.embedSWF("http://www.swatchmtvplayground.com/flash/mediaplayer/mediaplayer.swf", "mediaplayer"+i, "578", "345", "10.0.0", false, flashvars, params, attributes);
}
function pauseAllPlayers(exceptThisOne){
for(var i = 0 ; i < vids.length ; i++) if(exceptThisOne != "mediaplayer"+i) document.getElementById("mediaplayer"+i).pause();
}
to get the id I've used a neat little trick I didn't previously know about (executing JS created with actionscript) using Zeh Fernando's excellent guide: Getting the SWF’s HTML object/embed id from within the Flash movie itself
HTH
If you're using the same swf file three times you'd have to pass in a flash var to let the swf know which instance it is (video1, video2, or video3). Then when a video.swf instance starts playing use AS3's ExternalInterface to call JavaScript and mark that swf instance as the one currently playing.
Using SWFObject to embed the swfs in the page you can set the flashvars in JavaScript like this:
var flashvars1 = {
name: "video1",
};
swfobject.embedSWF("video1.swf", "flashContent1", "640", "480", "10.0.0", false, flashvars1, {}, {});
var flashvars2 = {
name: "video2",
};
swfobject.embedSWF("video2.swf", "flashContent2", "640", "480", "10.0.0", false, flashvars2, {}, {});
var flashvars3 = {
name: "video3",
};
swfobject.embedSWF("video3.swf", "flashContent3", "640", "480", "10.0.0", false, flashvars3, {}, {});
Within each swf you'll now have a 'name' var that can be accessed through LoaderInfo:
var name:String = LoaderInfo(this.root.loaderInfo).parameters.name;
And you call ExternalInterface from Flash like so:
ExternalInterface.call( "videoPlaying", name );
This would call a JavaScript function called 'videoPlaying' with the name as the argument:
function videoPlaying(name) {
// do something with the name arg
}
I have a preloader that is being served from a CDN, and I want it to load the target SWF also from the CDN but when it uses loaderInfo, it returns the hostname of the html file... Here's the setup:
index.html (hosted on primary domain) uses SWFObject to embed preloader
preloader.as hosted on remote CDN, contains code below
target.swf is to be loaded
I have inherited this code from another developer that I can't contact and I'm not an AS coder...
var url:String = "target.swf";
....
var request:URLRequest = new URLRequest(url);
loader = new Loader();
loader.load(request);
This is what I've tried, but I think it's returning the url of the index.html, not the CDN-hosted preloader:
var currentUrl:String = stage.loaderInfo.url;
var url:String = currentUrl.substring(0,currentUrl.length-13) + "target.swf";
....
Is there some way that I can get the URL that the preloader was served from which is the CDN?
Thanks,
Jonathan
stage.loaderInfo.url returns indeed the URL of the page displaying the swf. You may give your swf the address of the CDN as a parameter:
HTML
<script type="text/javascript">
var flashvars = {CDNroot:'http://mycdn/'
};
var params = {
menu: "false",
scale: "showAll",
allowFullscreen: "true",
allowScriptAccess: "always",
quality:"best",
bgcolor: "#FFFFFF"
};
var attributes = {
id:"main", name:"main"
};
swfobject.embedSWF("loader.swf", "altContent", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
</script>
Then to retrieve this parameter, use:
AS3
var url:String = stage.loaderInfo.parameters["CDNroot"] + "target.swf";
Is it possible in Javascript to pass a variable through the src parameter? ie.
<script type="text/javascript" src="http://domain.com/twitter.js?handle=aplusk" />`
I'd like twitter.js to look and see if a "handle" was passed before doing what I need it to do and returning its response back to the originating page calling twitter.js.
I had originally created a function in twitter.js that did the following:
function getHandle() {
var vars = [], hash, username;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash[0] == 'handle')
username = hash[1];
}
return username;
}
The problem, and it makes sense, is that window.location.href is not going to work on a file that I'm calling from <script src="" />
Thanks!
I can see two solutions here.
First: you can process those GET parameters on the server where the twitter.js is hosted, so that it will dynamically change the js file. For example, you file is:
var handle = {{ handle }};
And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.
The second option would be to set the global variables on the page where twitter.js is loaded, like this:
<script type="text/javascript">
window.twitter_js_handle = 'aplusk';
</script>
<script type="text/javascript" src="http://domain.com/twitter.js" />
And in twitter.js:
var handle = window.twitter_js_handle || null;
I use the following pattern to convert query variables from <script src="script.js?foo=bar&baz=zing"></script> to an object containing key:value pairs. Code is placed at the top of script.js:
var getVars = {};
(function(){
var scripts, currentScript, queryString;
scripts = document.getElementsByTagName('script');
currentScript = scripts[ scripts.length - 1 ];
queryString = currentScript.getAttribute('src').split("?").pop().split('&');
for(var i=0;i<queryString.length;i++){
var keyVal = queryString[i].split('=');
getVars[ keyVal[0] ] = keyVal[1];
}
}());
// console.info( getVars );
// Object { foo="bar", baz="zing"}
This probably won't work with deferred / asynchronously added script elements, as it relies on immediate code execution.
Sure. But the only way you can access that parameter though is through server-side. So, make twitter.js a PHP page (using mod_rewrite or whatever) that grabs $_GET['handle'] and then serves itself as Content-Type: text/javascript and just dump the contents of the js.
I suggest to use more safe approach - must add an ID:
<script id="myTargetScript" src="http://example.com/file.js?param=value" />
then in your .js file
function GetParams(target_id)
{
var getVars = {};
if( document.getElementById(target_id) )
{
var queryString = document.getElementById(target_id).getAttribute('src').split("?").pop().split("&");
for(var i=0;i<queryString.length;i++){
var keyVal = queryString[i].split('=');
getVars[ keyVal[0] ] = keyVal[1];
}
}
return getVars;
}
// console.log( GetParams('myTargetScript') );