0

この質問のタイトルが正しいかどうかわからないので、誰かがより良い説明を持っている場合は編集してください。

次のようにカスタム属性を持つ要素をアンカーしました(更新:@Runeソリューションと@Shaunaコメントによる)

<a href="#" class="call-method" data-url="/Pages/mustafa/test_dialoge.aspx/GetDate" data-data="" data-success="handleResult">call me</a>

data-url、data-data、data-success、data-error はカスタム属性です。

次に、次のスニペットを使用して、いくつかのスクリプトを添付します

$('.call-method').live('click', function () {

    var obj = $(this);
    var options = new Object();

    options.url = obj.attr('data-url').toString();
    options.success = obj.attr('data-success');
    options.error = obj.attr('data-error');
    options.complete = obj.attr('data-complete');

    var _options = JSON.stringify(options);

    callServerGetMethod(_options);

});


  var callServerGetMethod = function (options) {
    var _options = new Object();
    var self = this;
    if (typeof options === 'string') {
      _options = JSON.parse(options, function (key, value) {
        if (typeof self[value] === 'function') {
          return eval(self[value]);
        }
        return value;
      });
    }

    $.ajax(
      {
        type: "post",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        async: true,
        cache: false,
        error:
          function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.statusText);
            console.log(thrownError);
          }
      }, $.extend(_options));
  };

今、ブラウザコンソールに次のエラーが表示されました

SyntaxError {popStackFrame: function}
arguments: Array[1]
get message: function () { [native code] }
get stack: function () { [native code] }
set message: function () { [native code] }
set stack: function () { [native code] }
type: "unexpected_token"
__proto__: Error
arguments: undefined
constructor: function SyntaxError() { [native code] }
name: "SyntaxError"
stack: undefined
type: undefined
__proto__: d
4

1 に答える 1

2

関数ではなく文字列を ajax オプションに渡しているため、機能しません。

あなたの例では、あなたも書いたかもしれません

callServerGetMethod(url, data, function(msg) {
      alert("error " + msg);
    },
      function() {
        alert('comepleted');
      }
    , "handleSuccess");

最後の引数がプレーンな文字列であることに注意してください

代わりに、関数を渡す必要があります。これを行う最も一般的な方法は、カスタム属性ではなく JavaScript を使用して関数をアタッチすることです。

データ属性の扱い方によっては、その属性を使用できる場合があります。

<a href="#" 
   class="call-method" 
   options="{url: "/Pages/mustafa/test_dialoge.aspx/GetDate",data:{param1: 1, param2: 2}, success:handleResult,error:doOnError}"
>call me</a>

var callServerGetMethod = function (options) {
    var self = this;
    if(typeof options === 'string'){
      options = JSON.parse(options,function (key, value) {
         if (typeof self[value] === 'function') {
            return self[value];
         }
         return value;
      });
    }
    $.ajax($.extend({type: "POST"},options);
};

このように data 属性を使用できない場合は、単に属性値に基づいて options 引数を作成します

var call = function (url, data, onError, onComplete, onSuccess) {
    return callServerGetMethod('{"url":"' + url +'","data":' + data + ',"error":"' + onError + '","success":"' + onSuccess'"}');
}

または、文字列を定義済みの関数に変換する関数を定義することもできます

var string2function = function string2function(functionName){
     if (typeof functionName === 'function') return functionName;

     if(typeof functionName === 'string'){
         if (typeof self[functionName] === 'function') {
            return self[functionName];
         }
     }
     return null;
}

そして、このように使用します

options.success = string2function(obj.attr('data-success'));

eval理論的には属性値で使用できますがeval、その関数に関連する多くの潜在的なリスクがあるため、一般的には避けることをお勧めします

于 2013-02-11T13:59:54.390 に答える