Skip to content

Instantly share code, notes, and snippets.

@masterpoppy
Created December 4, 2016 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masterpoppy/f657e9618615a3796afca41013c7ab1e to your computer and use it in GitHub Desktop.
Save masterpoppy/f657e9618615a3796afca41013c7ab1e to your computer and use it in GitHub Desktop.
//***************************************************************
//ajaxで通信してさらに部分的に内容を書き換えるサンプル
//***************************************************************
//リクエストIDを保持する変数
key url_request;
//HTMLのコード
string HTML_BODY =
"<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<style type='text/css'>
body, input, button {
font-family: tahoma, arial, 'hiragino kaku gothic pro', meiryo, 'ms pgothic', sans-serif;
zoom: 200%;
}
</style>
<script>
$(function() {
$('button').click(function() {
var content = {};
content.text = $('#input').val();
content.click = $(this).attr('id');
if (content.text != '') {
$('#input').val('');
$.ajax({
'type': 'POST',
'url': location.href,
'dataType': 'json',
'data': JSON.stringify(content)
}).done(function(data) {
$('#output').html(data.text).css(data.style);
});
}
});
});
</script>
</head>
<body>
<div id='output'>ajaxのサンプル</div>
<p><input id='input' style='width:100%;'></p>
<button id='btn1'>赤で表示</button>
<button id='btn2'>青で表示</button>
</body>
</html>
";
default
{
state_entry()
{
//メディアをクリア(省略可)
llClearLinkMedia(LINK_THIS,4);
//http-inのサーバーURLをリクエスト
url_request = llRequestURL();
}
//装着したらリセット
attach(key attached)
{
llResetScript();
}
http_request(key id, string method, string body)
{
if (url_request == id)
{
url_request = "";
//サーバーURLが発行したらメディアを貼り付けてURLを設定する
if (method == URL_REQUEST_GRANTED){
integer status = llSetLinkMedia(LINK_THIS, 4, [
PRIM_MEDIA_HOME_URL, body,
PRIM_MEDIA_CURRENT_URL, body,
PRIM_MEDIA_AUTO_ZOOM, TRUE,
PRIM_MEDIA_AUTO_PLAY, TRUE,
PRIM_MEDIA_AUTO_SCALE, FALSE,
PRIM_MEDIA_WIDTH_PIXELS, 1024,
PRIM_MEDIA_HEIGHT_PIXELS, 1024,
PRIM_MEDIA_PERMS_INTERACT, PRIM_MEDIA_PERM_NONE,
PRIM_MEDIA_PERMS_CONTROL, PRIM_MEDIA_PERM_NONE
]);
}
}
else{
if(method == "GET" || method == "HEAD"){
//HTTP headerのContent-TypeをHTMLに設定してResponseする
llSetContentType(id, CONTENT_TYPE_HTML);
llHTTPResponse(id, 200, HTML_BODY);
}
else if(method == "POST"){
//入力テキストを取り出し
string text = llJsonGetValue(body, ["text"]);
//押したボタンidからCSSの文字色を選ぶ
string style_list = "{\"btn1\":{\"color\":\"red\"},\"btn2\":{\"color\":\"blue\"}}";
string style = llJsonGetValue(style_list, (list)llJsonGetValue(body, ["click"]));
//jsonオブジェクトに結合
string json = llList2Json(JSON_OBJECT, ["text",text,"style",style]);
//ContentTypeをJSONでResponse
llSetContentType(id, CONTENT_TYPE_JSON);
llHTTPResponse(id, 200, json);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment