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 而不是自定义属性附加函数。

Depending on how you treat the data attribute you might be able to use that attribute.

<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);
};

if you can't use the data attribute like this then simply construct the options argument based on the attribute values

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

alternatively you can define a function to turn a string into an already defined function

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;
}

and then use it like this

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

Theoretically you could use eval on the attribute value however it's generally encouraged to avoid evalbecause of a lot of potential riscs associated with that funciton

于 2013-02-11T13:59:54.390 回答