Skip to content

Instantly share code, notes, and snippets.

@Implem
Created November 15, 2015 20:10
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 Implem/0b2df8d6556b49a634e5 to your computer and use it in GitHub Desktop.
Save Implem/0b2df8d6556b49a634e5 to your computer and use it in GitHub Desktop.
jQuery: ajaxの戻り値Jsonでブラウザに色々なことをさせる共通ロジック ref: http://qiita.com/Implem/items/f703ebff141827c88dd3
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Implem.Pleasanter.Libraries.Responses
{
public class IssueModel
{
// 更新処理を行った後にクライアントのバージョンテキストボックスの内容更新と
// メッセージ領域へのメッセージ出力を命令します。
public string Update()
{
// 更新処理を記述。
// レスポンス処理。
return JsonConvert.SerializeObject(new Dictionary<string, string>
{
{ "#" + "#Issues_Ver", "3" },
{ ">", Title + "の更新が完了しました。" }
});
}
}
}
function request(requestUrl, methodType, data) {
return $.ajax({
url: requestUrl,
type: methodType,
cache: false,
data: data,
dataType: 'json'
})
.done(function (json, textStatus, jqXHR) {
if (json) {
// サーバーサイドから返却されたJsonを列挙
$.each(json, function (key) {
apply(key, this, data);
});
}
return true;
});
function apply(key, value, data) {
// keyの1文字目に含まれる命令記号を取得
var selector = key.substring(1, key.length);
// 処理対象のセレクタを選択
var $control = $(selector);
// Jsonに含まれる命令記号に基づき処理を分岐
switch (key.substring(0, 1)) {
case ' ': // htmlの書き換え命令
$control.html(value);
break;
case '>': // メッセージ領域への出力命令
setMessage(value);
break;
case '@': // 他のUrlへの遷移命令
location.href = value;
break;
case '_': // クライアントのデータ書き換え命令
data[$control.attr('id')] = value;
break;
case '+': // 要素の末尾に要素を追加する命令
$control.append(value);
break;
case '^': // 先頭に要素を追加する命令
$control.prepend(value);
break;
case '-': // 要素を削除する命令
$control.remove();
break;
case '.': // フォーカスをセットする命令
$control.focus();
break;
case '#': // 要素の値をセットする命令
setValue($control, value);
break;
case '$': // クライアント上のデータを書き換える命令
data[$control.attr('id')] = value;
setValue($control, value);
break;
case '%': // クライアント上のデータを消去する命令
clearFormData(selector, data);
break;
case ')': // clickなどイベントをキックする命令
$control.trigger(value);
break;
case '!': // 要素の内容を消去する命令
$control.empty();
break;
}
// メッセージ領域への出力
function setMessage(value) {
var $control = $('.message-dialog:visible');
if ($control.length == 0) {
$('#Message').html(value);
} else {
$control.html(value);
}
}
// 要素の値をセットする
function setValue($control, value) {
switch ($control.prop('type')) {
case 'checkbox':
$control.prop('checked', value);
break;
case 'radio':
$control.val([value]);
break;
default:
switch ($control.prop('tagName')) {
case 'SPAN':
$control.html(value);
default:
$control.val('' + value + '');
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment