jQuery token-input not processing cross-domain res

2019-09-06 08:12发布

I'm creating a chrome extension which uses http://loopj.com/jquery-tokeninput/ to add tokens, see previous question.

I am confused as to how to get results from my server to be processed by tokenInput. The following article, What is JSONP?, suggests that I need to add a callback query param to get cross-domain jsonp working:

$(function() {
  $("#token").tokenInput("http://localhost/token/search?callback=jsonprocess", {
    preventDuplicates: true,
    crossDomain: true,
  });
});

This is used to wrap the response in my php code:

header('Content-type: text/javascript');
echo $this->request->query('callback') . '(' . json_encode($token_array) . ')';
exit;

Which then calls the jsonprocess() method in my javascript. However this is out of context of the tokenInput instance so I can't populate the results. Is this the correct functionality? Or is there a way to make the jQuery tokeninput plugin process the jsonp directly?

The success callback in tokeninput:

ajax_params.success = function(results) {
    cache.add(cache_key, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
    if($.isFunction($(input).data("settings").onResult)) {
        results = $(input).data("settings").onResult.call(hidden_input, results);
    }
};

...is never called.

3条回答
做自己的国王
2楼-- · 2019-09-06 09:04

Dude you need callback in javascript and php like this:

javascript:

script.php?callback=?&your_parametars_here

and in php

echo $_GET['callback'].$your_data_here
查看更多
够拽才男人
3楼-- · 2019-09-06 09:06

As you can see in jQuery Tokeninput documentation, crossDomain must be set as true in options, if you want to it to be a jsonp request.

$(function() {
  $("#token").tokenInput("http://localhost/token/search?callback=jsonprocess", {
    preventDuplicates: true,
    crossDomain: true
  });
});

and The right JSON content type is application/json.

header('Content-type: application/json');

UPDATE:

Ok if it's not working with jsonp you should try it by enabling CORS.

Here what you will do,

$(function() {
  $("#token").tokenInput("http://localhost/token/search?callback=jsonprocess", {
    preventDuplicates: true,
    crossDomain: false, //it's also false as default.
  });
});

in PHP you must enable CORS, and you don't need to take result into the callback function. you will dump only JSON.

header("Access-Control-Allow-Origin: *");
header('Content-type: text/javascript');
echo json_encode($token_array);
exit;
查看更多
淡お忘
4楼-- · 2019-09-06 09:18

Easier than I thought; don't need ?callback=jsonprocess in the search url

$(function() {
  $("#token").tokenInput("http://localhost/token/search", {
    preventDuplicates: true,
    crossDomain: true,
  });
});
查看更多
登录 后发表回答