使用Javascript从任何网站表单存储输入数据并将其发送到Webhook

时间:2019-06-08 14:19:35

标签: javascript json ajax

我要配置一些Javascript代码,以将捕获的表单数据发送到Webhook。

var name = document.getElementById("pwebcontact1_field-name").value;
var email = document.getElementById("pwebcontact1_field-email").value;
var phone = document.getElementById("pwebcontact1_field-phonenumber").value;
var zillow = document.getElementById("pwebcontact1_field-yourzillowprofilelinkcopyandpastehere").value;

var data = {
name: name.value,
email: email.value,
phone: phone.value,
zillow: zillow.value
};

$.ajax({
url: 'url',
method: 'POST',
contentType: 'application/json',
crossDomain: true,
headers: {
    'authkey': 'key'
},
data: JSON.stringify(data)    
})
.success(function(response) {
console.log(response);
});

已配置URL和authkey。 Webhook收到通知,但主体为空。钩子的发布者提供的用于发布正文的示例是:

"data": "{\"hello\":\"world\"}"

在反斜杠转义的地方添加引号。我想我需要在引号之间的那个代码块中获取数据字段。

谢谢!

2 个答案:

答案 0 :(得分:1)

首先,检查所有地方的元素是否使用正确的ID。如果是,请尝试以下操作:

var name = document.getElementById("pwebcontact1_field-name").value;
var email = document.getElementById("pwebcontact1_field-email").value;
var phone = document.getElementById("pwebcontact1_field-phone").value;
var zillow = document.getElementById("pwebcontact1_field-zillow").value;

var data = {
    name: name,
    email: email,
    phone: phone,
    zillow: zillow
};

$.ajax({
    url: 'YOUR_URL',
    method: 'POST',
    contentType: 'application/json',
    crossDomain: true,
    headers: {
        'authkey': 'x'
    },
    data: JSON.stringify(data)    
})
.success(function(response) {
    console.log(response);
});

不过,您应该注意验证输入内容。


评论后编辑:

您在选择中使用了错误的ID。使用上面的代码,但将“ phone”和“ zillow”变量分配交换为以下内容:

var phone = document.getElementById("pwebcontact1_field-phonenumber").value;
var zillow = document.getElementById("pwebcontact1_field-yourzillowprofilelinkcopyandpastehere").value;

评论2之后的编辑: 您发布到的端点很可能无法正确解析请求正文。可能期望使用不同的结构或格式(MIME类型)。记下您对作者如何建议发送数据以及所提供示例的评论,我们排除了MIME类型的问题,并认为它是JSON。在结构中也是如此。我们需要将当前数据对象(数据属性)包装在“数据”属性中。

尝试:

var data = {
    data: {
        name: name,
        email: email,
        phone: phone,
        zillow: zillow
    }
};

答案 1 :(得分:1)

非常感谢@Zhulien,有效的修改后的代码是:

var name = document.getElementById("pwebcontact1_field-name").value;
var email = document.getElementById("pwebcontact1_field-email").value;
var phone = document.getElementById("pwebcontact1_field-phonenumber").value;
var zillow = document.getElementById("pwebcontact1_field-yourzillowprofilelinkcopyandpastehere").value;

var data = {
 data: {
    name: name,
    email: email,
    phone: phone,
    zillow: zillow
 }
};

$.ajax({
 url: 'YOUR_URL',
 method: 'POST',
 contentType: 'application/json',
 crossDomain: true,
 headers: {
  'authkey': 'x'
 },
data: JSON.stringify(data)    
})
.success(function(response) {
console.log(response);
});

这是您可以从任何网站表单存储和发送数据输入字段以发送到Webhook的方式!

相关问题