我想发布一个json对象。我相信我很接近,但数据没有正确发送。
数据格式正确的json字符串,它与ajax一起正常工作。但是,需要根据REST请求重定向页面。显然使用ajax,这不会发生。
var data = JSON.stringify(myJsonObject);
$('<form enctype="application/json" action="/projects" method="POST">' +
'<input type="hidden" name="json" value="' + data + '">' +
'</form>').submit();
答案 0 :(得分:4)
我认为您需要转义字符串化的JSON。
var data = $(JSON.stringify(myJsonObject);
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
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();
答案 1 :(得分:1)
您的JSON字符串包含引号,它会破坏html。
修改:如果你不在乎隐藏输入中的可读格式,你也可以使用转义(字符串)。然后你可以使用 unescape(string)来取回你的json字符串。这样你就可以使用相同的函数将它传递给get请求;)
{name: "test"}
==> %7B%22name%22%3A%22test%22%7D
答案 2 :(得分:0)
Curl
怎么样,你可以发布这样的数据。你需要一个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;
}
此函数发送一个json并从API返回。
答案 3 :(得分:0)