How do I get a json answer in javascript/jquery?

Asked

Viewed 425 times

2

I have the link:

https://dominio.com/apiJSON.php?data={"login":"[email protected]","senha":"Minhasenha","campanha":"ID 1234","mensagens":{"1":{"numero":2799999999,"msg":"Uma mensagem qualquer","data":"2015-10-19 01:07:52"}}}

Pasting this link in the browser with the correct parameters gets the following answer in the browser:

{"tip":1,"msg":[{"numero":2799999999,"id":"1234","status":1}]}

I want to take this answer and work on it in javascript or jquery. I need to work on this information. Can anyone help me? Thanks!!!

Note: I asked this question and I got it in php. However I need to work it in another language because php the server barred.

2 answers

1

Make an ajax call I think is the best way, taking into account that your question is javascript I will post accordingly, keep in mind that with jquery or other libs could greatly reduce this code:

var xmlhttp;
var data;

if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
       if(xmlhttp.status == 200){
           data = xmlhttp.responseText;
       }
       else if(xmlhttp.status == 400) {
           alert('There was an error 400')
       }
       else {
           alert('something else other than 200 was returned')
       }
    }
};

xmlhttp.open("GET", 'https://dominio.com/apiJSON.php?data={"login":"[email protected]","senha":"Minhasenha","campanha":"ID 1234","mensagens":{"1":{"numero":2799999999,"msg":"Uma mensagem qualquer","data":"2015-10-19 01:07:52"}}}', true);
xmlhttp.send();

// agora vamos tranformar a string JSON num objeto de javascript caso o pedido tenha sido bem sucedido:
if (typeof data != 'undefined') {
    data = JSON.parse(data);
}
console.log(data);
  • Vlw friend. I will try here and return you.

0


Thiago, it seems a little strange to pass a json as a string to an API, especially by GET.

but you can consume this URL in two ways: AJAX or JSONP:

AJAX

var json = {
    "login":"[email protected]",
    "senha":"Minhasenha",
    "campanha":"ID 1234",
    "mensagens":{
        "1":{
            "numero":2799999999,
            "msg":"Uma mensagem qualquer",
            "data":new Date(2015, 9, 19, 1, 7, 52)
        }
    }
};

var data = new FormData();
data.append("data", JSON.stringify(json)):

var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "https://dominio.com/apiJSON.php", true);
httpRequest.responseType = "json";
httpRequest.addEventListener("readystatechange", function (event) {
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            console.log(httpRequest.response): //seu objeto JSON;
            /* Faça alguma coisa com o "httpRequest.response" */
        } else {
            console.log("Ocorreu um Erro");
        }       
    }
})
httpRequest.send(data);

JSONP

Note that I added another argument to your URL, callback=minhaFuncao, the callback parameter defines the name of the function that will receive the json object obtained as return of the request.

var json = {
    "login":"[email protected]",
    "senha":"Minhasenha",
    "campanha":"ID 1234",
    "mensagens":{
        "1":{
            "numero":2799999999,
            "msg":"Uma mensagem qualquer",
            "data": new Date(2015, 9, 19, 1, 7, 52)
        }
    }
};  

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://dominio.com/apiJSON.php?data=" + JSON.stringify(json) + "&callback=minhaFuncao";
var minhaFuncao = function(data) {  
    /* data é o objeto JSON retornado pelo script acima */
}
document.head.appendChild(script);
  • Vlw, I’ll try your example and return you friend!

  • HI, sorry my ignorance, but how do I get the result of this function? Actually what I need is only the campaign parameter. Can you help me?

  • @Thiago, campaign is in your json used on request, then to access it you do not need to make a request, either by AJAX or JSONP... just use var campanha = json.campanha;

  • I understood. It is that there is a parameter called balance, which would be like this in your code: ( "balance" : "" ), yes it is empty. Ai when executing the json link it returns the balance number. When I try to do as you say it returns only the value you have above. How to proceed?

  • @Thiago, in the example above, you can access the response in the commented part of the code, for example, if the return is { saldo: "" } then use var saldo = httpRequest.response.saldo; (AJAX) or var saldo = data.saldo; (JSON).

  • In json it would be balance = date.balance or balance = json.?

  • @Thiago, if you use JSONP, sera data.saldo

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.