Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Tampermonkey и GET\POST запрос с выводом ответа (https://javascript.ru/forum/events/46459-tampermonkey-i-get%5Cpost-zapros-s-vyvodom-otveta.html)

XRASER 10.04.2014 19:20

Tampermonkey и GET\POST запрос с выводом ответа
 
Необходимо кинуть запрос на php файл (GET или POST, без разницы) с переменной "sid=demo" и вывести ответ alert'ом.

Пример, который нашел здесь, почему-то у меня не работает.

Код:
// ==UserScript==
// @id test
// @name Test
// @namespace test
// @match [url]http://en.wikipedia.org/*[/url]
// ==/UserScript==

var GM_xmlhttpRequest = function (params) {
    var req = new XMLHttpRequest();
    
    req.open(params.method, params.url);
    
    for (var header in params.headers) {
        req.setRequestHeader(header, params.headers[header]);
    }
    
    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            params.onload(req);
        }
    };
    
    req.send(params.data);
};

var query = {
    method: "POST",
    url: "https://en.wikipedia.org/w/api.php",
    onload: function (res) {
        alert(res.responseText);
    },
};

query.data = "action=query&meta=siteinfo&format=json";
query.headers = {"Content-type": "application/x-www-form-urlencoded"};

GM_xmlhttpRequest(query);

XRASER 12.04.2014 19:08

Вот так работает:

jQuery.ajax = (function(_ajax) {

    var protocol = location.protocol,
        hostname = location.hostname,
        exRegex = RegExp(protocol + '//' + hostname),
        YQL = 'http' + (/^https/.test(protocol) ? 's' : '') + '://query.yahooapis.com/v1/public/yql?callback=?',
        query = 'select * from html where url="{URL}" and xpath="*"';

    function isExternal(url) {
        return !exRegex.test(url) && /:\/\//.test(url);
    }

    return function(o) {

        var url = o.url;

        if (/get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url)) {

            // Manipulate options so that JSONP-x request is made to YQL

            o.url = YQL;
            o.dataType = 'json';

            o.data = {
                q: query.replace(
                    '{URL}',
                    url + (o.data ?
                        (/\?/.test(url) ? '&' : '?') + jQuery.param(o.data) : '')
                ),
                format: 'xml'
            };

            // Since it's a JSONP request
            // complete === success
            if (!o.success && o.complete) {
                o.success = o.complete;
                delete o.complete;
            }

            o.success = (function(_success) {
                return function(data) {

                    if (_success) {
                        // Fake XHR callback.
                        _success.call(this, {
                            responseText: data.results[0]
                            // YQL screws with <script>s
                            // Get rid of them
                            .replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
                        }, 'success');
                    }

                };
            })(o.success);

        }

        return _ajax.apply(this, arguments);

    };

})(jQuery.ajax);

$.ajax({
            url: 'http://wotbonuscode.tk/getcode.php',
            type: 'GET',
            success: function(res) {
                alert(res.responseText);
            }
        });


Но возвращает:

Код:

<html>
  <head>
    <meta content="HTML Tidy for Java (vers. 26 Sep 2004), see www.w3.org" name="generator"/>
    <title/>
  </head>
  <body>
    <p>TESTCODE</p>
  </body>
</html>

А мне нужно просто "TESTCODE", как это сделать?

Aetae 12.04.2014 19:25

Возвращать только TESTCODE.

XRASER 12.04.2014 20:37

Так:

$.ajax(
{
	url: 'http://wotbonuscode.tk/getcode.php',
	type: 'GET',
	dataType: 'html',
	success: function(res)
   	{
	alert(res.responseText);
	}
});


Или так:
$.get( "http://wotbonuscode.tk/getcode.php", function( data ) {
  alert( "data );
});


Запрос отправляется, а ответ не выводит.

jsnb 14.04.2014 03:31

Цитата:

Сообщение от XRASER (Сообщение 307440)
Так:
$.ajax(
{
	url: 'http://wotbonuscode.tk/getcode.php',
	type: 'GET',
	dataType: 'html',
	success: function(res)
   	{
	alert(res.responseText);
	}
});

Заменить res.responseText на res.
Запрос отправляется с того же домена, где и лежит php скрипт?

Ilya_Nsk 16.04.2014 14:10

кроссдоменные запросы режутся броузером, если сервер не говорит что можно.


Часовой пояс GMT +3, время: 05:17.