Articulate Storyline 360中JavaScript实现HTTP POST发送变量求助
问题:Articulate Storyline 360 实现POST请求发送数据到PHP服务器
背景与已完成工作
- 培训材料托管在LMS,需要用Articulate Storyline 360通过POST把课程相关数据(Forename、Surname、Depot)发送到指定PHP文件
- 已经成功用JavaScript获取到Storyline里的变量,测试代码如下:
var player = GetPlayer(); alert("Welcome back, " + player.GetVar("Forename") + ".");
当前遇到的问题
POST功能完全没效果:既没弹出成功提示,目标服务器也没收到任何数据。现在写的POST代码是Java语法,根本不适用JavaScript环境。
接收端PHP代码
// takes raw data from the request $data = file_get_contents("php://input"); $json = json_decode($data); //Get Variables $forename = $json['Forename']; $surname = $json['Surname']; $depot = $json['Depot'];
当前错误的POST代码(Java语法)
//get variables and build JSON var player = GetPlayer(); JSONObject json = new JSONObject(); json.put("Forename", player.GetVar("Forename")); json.put("Surname", player.GetVar("Surname")); json.put("Depot", player.GetVar("Depot")); //post CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try { HttpPost request = new HttpPost("https://flashpoint.flogas.co.uk/assurance/include/tasks/dmbctest.php"); StringEntity params = new StringEntity(json.toString()); request.addHeader("content-type", "application/json"); request.setEntity(params); httpClient.execute(request); // handle response here... } catch (Exception ex) { // handle exception here } finally { httpClient.close(); alert("Details have been sent..."); }
正确的JavaScript POST实现方案
用浏览器原生的fetch API就行,Storyline 360的运行环境完全支持,代码如下:
var player = GetPlayer(); // 组装要发送的JSON数据 var postData = { Forename: player.GetVar("Forename"), Surname: player.GetVar("Surname"), Depot: player.GetVar("Depot") }; // 发送POST请求 fetch("https://flashpoint.flogas.co.uk/assurance/include/tasks/dmbctest.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(postData) }) .then(function(response) { // 处理请求结果 if (response.ok) { alert("Details have been sent..."); } else { alert("发送失败,请重试"); } }) .catch(function(error) { // 捕获网络错误 alert("发送出错:" + error.message); });
额外注意事项
PHP端代码有个小bug:json_decode($data)默认返回的是对象,用$json['Forename']这种数组方式访问会报错,需要改成下面两种方式之一:
- 把对象转为关联数组:
$json = json_decode($data, true); // 加第二个参数true,转为关联数组 $forename = $json['Forename']; $surname = $json['Surname']; $depot = $json['Depot'];
- 用对象属性的方式访问:
$forename = $json->Forename; $surname = $json->Surname; $depot = $json->Depot;
内容的提问来源于stack exchange,提问作者JKG79
相关产品推荐
相关产品推荐

