简体   繁体   English

发布没有ajax或表单的JSON数据

[英]Post JSON data without ajax or form

I have a json object that I would like to post. 我有一个要发布的json对象。 I beleive that Im close but the data isnt getting sent correctly. 我相信即时通讯已关闭,但数据未正确发送。

data is correctly formatted json string and it works correctly with ajax. 数据格式正确的json字符串,并且可以与ajax一起正常使用。 However, the page needs to be redirected according to the REST api im requesting. 但是,该页面需要根据REST API的请求进行重定向。 Obviously using ajax, this wouldn't happen. 显然,使用ajax不会发生。

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. 我认为您需要转义字符串化的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. 您的JSON字符串包含引号,并且会中断html。

Edit: You can also use escape(string) if you don't care if it is in readable format in the hidden input. 编辑:如果您不在乎隐藏输入中的格式是否可读,也可以使用escape(string) Then you can use unescape(string) to get back your json string. 然后,您可以使用unescape(string)来获取json字符串。 That way you can use the same function to pass it over get requests too ;) 这样,您也可以使用相同的函数将其传递给get请求;)

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

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

What about Curl you could post you data like so. Curl可以这样发布数据呢? You will need a ajax call the PHP function : 您将需要ajax调用PHP函数:

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. 该函数发送一个json并从API获取返回值。

you can do this but id redirect the page. 您可以执行此操作,但ID重定向页面。 other solution is using $.Ajax or $.post 其他解决方案是使用$ .Ajax$ .post

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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