英文:
Passing post via Ajax
问题
以下是翻译好的内容:
表单页面:
<script>
function metatags() {
var url = $('#url').val;
jQuery.ajax({
url: "inc/recoverData.php",
type: "POST",
data: 'url=' + url,
dataType: 'JSON',
success: function(html) {
$('#domain').val(html.domain);
$('#title').val(html.title);
$('#description').val(html.description);
}
})
}
</script>
PHP页面:
<?php
$url = 'https://www.stackoverflow.com'; // WORKS
$url = 'https://www.' . $_POST['url']; // DOESN'T WORK
$metaTags = get_meta_tags($url);
$description = $metaTags['description'];
$domain = parse_url($url, PHP_URL_HOST);
$title = getTitle($url);
$data = [
"description" => $description,
"domain" => $domain,
"title" => $title
];
echo json_encode($data);
If I pass url via Ajax, script doesn't work
英文:
I need to autocomplete a form with some metadata according to the URL provided.
Form page:
<script>
function metatags() {
var url = $('#url').val;
jQuery.ajax({
url: "inc/recoverData.php",
type: "POST",
data: 'url=' + url,
dataType: 'JSON',
success: function(html) {
$('#domain').val(html.domain);
$('#title').val(html.title);
$('#description').val(html.description);
}
})
}
</script>
PHP page
<?php
$url = 'https://www.stackoverflow.com'; // WORKS
$url = 'https://www.' . $_POST['url']; // DOESNT WORKS
$metaTags = get_meta_tags($url);
$description = $metaTags['description'];
$domain = parse_url($url, PHP_URL_HOST);
$title = getTitle($url);
$data = [
"description" => $description,
"domain" => $domain,
"title" => $title
];
echo json_encode($data);
If I pass url via Ajax, script doesn't works
答案1
得分: 2
- 你正在传递错误的数据。在ajax中,以对象的形式传递数据。
- 你在使用
val
获取值。而在Jquery中,可以使用val()
来获取值。
以下是更新后的代码:function metatags() { var url = $('#url').val(); jQuery.ajax({ url: "inc/recoverData.php", type: "POST", data: {url: url}, dataType: 'JSON', success: function(html) { $('#domain').val(html.domain); $('#title').val(html.title); $('#description').val(html.description); } }) }
。你可以在JQuery文档中阅读更多。
英文:
- You are passing data incorrect. Pass the data as an object in ajax.
- You are using val for value. While in Jquery, the value can be get with val().
Here is the updated Code:-
function metatags() {
var url = $('#url').val();
jQuery.ajax({
url: "inc/recoverData.php",
type: "POST",
data: {url: url},
dataType: 'JSON',
success: function(html) {
$('#domain').val(html.domain);
$('#title').val(html.title);
$('#description').val(html.description);
}
})
}
You can read more in JQuery Docs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论