我正在使用上面的方法&它与URL中的一个参数一起工作得很好。
例如,应用控制器/动作/参数格式的Students/getstud/1
。
现在我在学生控制器中有了一个动作,它接受两个参数并返回一个JSON对象。
那么,如何使用post方法通过$.getJSON()
发布数据呢?
类似的方法也是可以接受的。
重点是使用AJAX调用控制器的操作。
发布于 2009-04-15 11:59:16
$.getJSON()方法执行HTTP GET而不是POST。您需要使用$.post()
$.post(url, dataToBeSent, function(data, textStatus) {
//data contains the JSON object
//textStatus contains the status: success, error, etc
}, "json");
在调用中,dataToBeSent
可以是您想要任何东西,尽管如果要发送html表单的内容,您可以使用serialize方法从表单创建帖子的数据。
var dataToBeSent = $("form").serialize();
发布于 2010-09-29 11:49:17
这是我的“一行”解决方案:
$.postJSON = function(url, data, func) { $.post(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }
为了使用jsonp和POST方法,此函数将"callback“GET参数添加到URL。这是它的使用方法:
$.postJSON("http://example.com/json.php",{ id : 287 }, function (data) {
console.log(data.name);
});
服务器必须准备好处理回调GET参数,并将json字符串返回为:
jsonp000000 ({"name":"John", "age": 25});
其中"jsonp000000“为回调GET的值。
在PHP中,该实现如下所示:
print_r($_GET['callback']."(".json_encode($myarr).");");
我做了一些跨域测试,它似乎起作用了。不过,仍然需要更多的测试。
发布于 2015-03-16 02:08:13
只需将以下代码行添加到您的<script>
(在加载jQuery之后但在发布任何内容之前的某个位置):
$.postJSON = function(url, data, func)
{
$.post(url, data, func, 'json');
}
用$.postJSON
替换(部分/全部) $.getJSON
,尽情享受吧!
您可以使用与$.getJSON
相同的Javascript回调函数。不需要对服务器端进行更改。(嗯,我总是推荐在PHP中使用$_REQUEST
。http://php.net/manual/en/reserved.variables.request.php,Among $_REQUEST, $_GET and $_POST which one is the fastest?)
这比@lepe的解决方案更简单。
https://stackoverflow.com/questions/751218
复制相似问题