简体   繁体   中英

Post JSON data without ajax or form

I have a json object that I would like to post. I beleive that Im close but the data isnt getting sent correctly.

data is correctly formatted json string and it works correctly with ajax. However, the page needs to be redirected according to the REST api im requesting. Obviously using ajax, this wouldn't happen.

var data = JSON.stringify(myJsonObject);

$('<form enctype="application/json" action="/projects" method="POST">' + 
  '<input type="hidden" name="json" value="' + data + '">' +
  '</form>').submit();

I think you need to escape your stringified JSON.

var data = $(JSON.stringify(myJsonObject);

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };

  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

$('<form enctype="application/json" action="/projects" method="POST">' + 
  '<input type="hidden" name="json" value="' + escapeHtml(data) + '">' +
  '</form>').submit();

Your JSON string contains quotes and it breaks the html.

Edit: You can also use escape(string) if you don't care if it is in readable format in the hidden input. Then you can use unescape(string) to get back your json string. That way you can use the same function to pass it over get requests too ;)

{name: "test"}
==>  %7B%22name%22%3A%22test%22%7D 

Example: https://stackoverflow.com/a/17696884/986160

What about Curl you could post you data like so. You will need a ajax call the PHP function :

function sendData($json){

    $url = 'wwww.exemple.com';



    //setting the curl parameters.

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    // Following line is compulsary to add as it is:

    curl_setopt($ch, CURLOPT_POSTFIELDS,$json);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);

    $data = curl_exec($ch);



    curl_close($ch);



    return $data;





}

This function send a json and get the return from API.

you can do this but id redirect the page. other solution is using $.Ajax or $.post

var form = $('<form enctype="application/json" action="/projects" method="POST">' + 
  '<input type="hidden" name="json" value="' + data + '">' +
  '</form>');
form.submit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM