Отправка post запроса на чужой домен задача часто встречающаяся. Как оказалось работающего решения у нее нет. Есть лишь пара "костыльных" вариантов.
Первый, и самый работающий это jsonp. Однако jsonp - это GET запрос. Т.е. количество данных переданных за один запрос в разных ситуациях не может превышать 1024 байта, или другого значения. Зависит то ли от настроек браузера, то ли от настроек сервера.
Объясню, что такое jsonp. При jsonp запросе, в документе динамически создается элемент <script>, его атрибуту src присваивается url содержащий все данные, которые Вы хотите передать на сервер. Затем, элемент присоединяется к документу и в этот момент происходит запрос на сервер. В ответ, сервер может вернуть js код, который выполниться после загрузки. Обычно в одним из параметров в src скрипта подают еще название callback функции, которую нужно будет вызвать. Рассмотрим подробнее
Вот js код отправки данных
var callback_me = function( data ){ alert(data.id+'загружен'); } var script = document.createElement('script'); // создаем элемент script.src = 'http://xdan.ru/data.php?callback=callback_me&id=123&name=masha&famaly='+encodeURIComponent('Петровна'); document.body.appendChild( script ); // добавляем элемент в документ, в этот момент и происходит запрос
и php код на сервере
<?php $id = $_GET['id']; $name = $_GET['name']; // но обычно использую $_REQUEST, чтобы иметь совместимость с обычным post запросом $famaly = $_REQUEST'famaly']; $callback = $_REQUEST'callback']; echo $callback.'('.json_encode(array('id'=>$id)).')'; exit();
в результате в script загружается такой код
callback_me({id:123});
в результате вызывается необходимая функция, в которой можно произвести какие-то манипуляции с пришедшими данными.
Вот и все. Но, как я уже написал выше это GET запрос, что бы Вам не говорили. Даже модный jquery.getJSON тоже работает на GET запросе.
Остаются еще пару вариантов: делать все через flash и использовать iframe с формой. Оба костыльные. Как я и предупреждал отправка post запроса на другой домен задача не тривиальная. Проще разработать свой сайт
Для варианта с flash есть немало заморочек. Я его не пробовал, просто потому, что флеш невзлюбил еще на заре его появления. Теперь по мере развития html5 это нелюбовь только усиливается. Однако, как пишут на форумах, вариант рабочий. Чтобы он сработал. и флеш мог отправлять данные необходимо чтобы на Вашем (другом) сервере лежал файл crossdomain.xml с таким содержанием
<?xml version="1.0" ?> <cross-domain-policy> <allow-access-from domain="*.domain1.ru" /> </cross-domain-policy>
Способ с iframe весьма хорош. Отправлять можно все что угодно, можно отправлять даже файлы, но у него есть один минус. Он не вызывает callback функцию. Т.е. нельзя узнать отправились ли данные и что вернул сервер. Так как это единственный верный способ отправлять большие объемы данных, то я воспользовался именно им. А чтобы узнать все ли хорошо с данными, которые Вы отправили можно после такого запроса отправить классический jsonp с неким параметром, к примеру id и в ответ сервер вернет данные по запросу с этим id. Понятно, что iframe запрос тоже нужно слать с этим же id. Подробнее расскажу в комментариях, если кого заинтересовало.
Немного разбавлю теорию куском кода, чтобы было понятно, как работать с iframe
function iploader( url,data ){ var frame = document.createElement('iframe'); //frame.style.display = 'none'; document.body.appendChild(frame); var doc = frame.contentDocument || frame.contentWindow.document; doc.open(); var s = ''; for( var c in data ){ s+='<input type="hidden" name="'+c+'" value="'+ (data[c]+'') .replace(/&/g, '&').replace(/"/g, '"') .replace(/'/g, ''') .replace(/</g, '<') .replace(/>/g, '>')+ '"/>'; } doc.write( '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><form accept-charset=UTF-8 enctype="application/x-www-form-urlencoded" id="ex_form" action="'+url+'" method="post">'+s+'</form></body></html>' ); doc.close(); doc.getElementById('ex_form').submit(); } iploader('http://xdan.ru/con.php',{id:23455,asaa:342423,sdfsd:456456,rtrt:'zxxcz zxczx " czxczxc zx zxczxczxczx czxczxc'});
Комментарии
enjoyment, for the reason that this this website conations
really fastidious funny information too.
It contains fastidious material.
but it appears a lot of it is popping it up all over the internet without my
agreement. Do you know any ways to help protect against content from being stolen?
I'd really appreciate it.
Thanks so much and I am looking forward to touch you.
Will you please drop me a mail?
a quick visit this blog on regular basis to take updated from most up-to-date reports.
to ask. Does operating a well-established website like yours take a lot of work?
I am brand new to operating a blog however I do write in my diary on a daily basis.
I'd like to start a blog so I will be able to share my own experience and feelings online.
Please let me know if you have any ideas or tips for new aspiring
blog owners. Appreciate it!
a part 2?
after I clicked submit my comment didn't show up.
Grrrr... well I'm not writing all that over again. Anyhow, just wanted to say excellent
blog!
I've joined your rss feed and stay up for in quest
of more of your wonderful post. Also, I've shared your web
site in my social networks
am going to deliver in university.
I don't know who you are but certainly you are going
to a famous blogger if you are not already ;
) Cheers!
I don't know the reason why I cannot join it. Is there anybody having the same RSS problems?
Anyone who knows the answer will you kindly respond?
Thanks!!
I have saved as a favorite for later!
read everthing at single place.
never seem to get nearly anything done.
I'm hoping to start my own blog soon but I'm a little lost on everything.
Would you suggest starting with a free platform like Wordpress or go
for a paid option? There are so many options out there
that I'm completely overwhelmed .. Any ideas?
Thanks!
you make blogging look easy. The overall look of your site is
fantastic, as well as the content!
It will always be interesting to read through content from other
writers and practice something from their sites.
you amend your website, how can i subscribe for a blog web site?
The account helped me a acceptable deal. I had been tiny bit
acquainted of this your broadcast provided bright clear concept
Is this a paid theme or did you modify it yourself?
Either way keep up the nice quality writing, it is
rare to see a great blog like this one today.
Glance complex to far added agreeable from you! However, how can we communicate?
I'm trying to find out if its a problem on my end or if it's the blog.
Any feed-back would be greatly appreciated.
of your website? Its very well written; I love what youve got to say.
But maybe you could a little more in the way of content so people could connect with it
better. Youve got an awful lot of text for only having one or two images.
Maybe you could space it out better?
I do not know who you are but definitely you are going to a
famous blogger if you are not already ;) Cheers!
in my view its truly awesome designed for me.
I've loaded your blog in 3 completely different
internet browsers and I must say this blog loads a lot quicker
then most. Can you recommend a good hosting provider at a reasonable price?
Thank you, I appreciate it!
weblog or even a blog from start to end.
I'll probably be returning to read more, thanks for the information!
I've got some ideas for your blog you might be interested in hearing.
Either way, great blog and I look forward to seeing it grow over time.
earlier technologies, it's awesome article.
The arena hopes for even more passionate writers such as you who aren't afraid to say how they believe.
At all times follow your heart.
could assume you're an expert on this subject. Fine with your permission let me
to grab your feed to keep updated with forthcoming
post. Thanks a million and please continue the
gratifying work.
work and exposure! Keep up the excellent works
guys I've added you guys to my personal blogroll.
can i do it please help.
I don't understand the reason why I cannot subscribe to
it. Is there anyone else having the same RSS issues? Anyone that knows the answer will you kindly respond?
Thanx!!
care! Exactly where are your contact details though?
I am going to highly recommend this blog!
I like what I see so now i am following you. Look forward
to exploring your web page again.
if so after that you will without doubt get good know-how.
written by him as nobody else know such detailed about my difficulty.
You are wonderful! Thanks!
Your website offered us with helpful info to work on. You've
performed a formidable activity and our whole group will probably be thankful to you.
nice job.
actually nice.
I have no knowledge of coding however I had been hoping to start my own blog
soon. Anyways, if you have any ideas or techniques for new blog owners please share.
I know this is off subject however I simply had to ask.
Thanks a lot!
And i'm glad reading your article. But should remark on few general things, The site
style is wonderful, the articles is really great : D.
Good job, cheers
It kind of feels that you are doing any distinctive trick.
Moreover, The contents are masterwork. you have done a fantastic process on this matter!
it helped me out a lot. I hope to present something back and aid others such as you aided me.
Is anyone else having this issue or is it a issue
on my end? I'll check back later and see if the problem still exists.
keep up the good work!
I have always disliked the idea because of the costs.
But he's tryiong none the less. I've been using Movable-type on a variety of websites for about a
year and am concerned about switching to another platform.
I have heard excellent things about blogengine.net.
Is there a way I can import all my wordpress content into it?
Any kind of help would be really appreciated!
RSS лента комментариев этой записи