Ajax call from Bookmarklet

限于喜欢 提交于 2019-11-27 15:10:22

问题


I am trying to create a bookmarklet that, upon clicking, would request some information from the user (a url and a couple other fields in this case) and then send that data to a php page on my server and then display the result.

I would like to do an Ajax call for this so that I don't actually redirect to the new page, just get the data but I assume I would run into the "Same Origin Policy" limitation of Ajax.... is there any known way of basically doing the same thing?

Also, what would be the best way to pass the parameters? I already have a mechanism in place to recieve the parameters as a post message from a form...is there any way I could just reuse this?


回答1:


You can set a bookmarklet by create a bookmark and add that piece of code below in location, but, according to same origin policy limitation, that will only work when the current tab is on the same location, here www.google.com.

If I've understand well your needs, that should be ok for your problem.

var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com", true);
request.onreadystatechange = function() {
  var done = 4, ok = 200;
  if (request.readyState == done && request.status == ok) {
    if (request.responseText) {
      alert(request.responseText);
    }
  }
};
request.send(null);

I don't know if POST would work.




回答2:


You won't be able to do a post, but a GET will work fine. If you're using something like jQuery, it will simply create a script tag with a src URL which would send the data you are looking to submit.

You will have to return JSON style data.

See: http://docs.jquery.com/Ajax/jQuery.getJSON

Alternatively, your bookmarklet could create an iframe on the page, and that could do you work of submitting the data (you could use post then) if you weren't looking to communicate between the iframe and the page itself, but instead just use user input to submit.



来源:https://stackoverflow.com/questions/664689/ajax-call-from-bookmarklet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!