我开发了一个chrome扩展,我通过django服务在mysql中插入json数据。我想将数据从django发送到chrome扩展名的java脚本。 popup.js:
document.addEventListener('DOMContentLoaded', documentEvents, false);
function myAction(fname,femail,fpassword) {
var str = "name="+ fname.value + "&email=" + femail.value + "&password=" + fpassword.value;
var xmlhttp = new XMLHttpRequest();
alert(str);
var theUrl = "http://127.0.0.1:8000/polls/?";
xmlhttp.open("POST", theUrl, true);
xmlhttp.onreadystatechange = function() {
//alert(xmlhttp.readyState + " " + xmlhttp.status);
if (xmlhttp.readyState == 4){
alert("entered");
}
else{
alert("not entered");
}
};
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send(str);
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
var theUrl = "http://127.0.0.1:8000/polls/?";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseText;
}
};
xhttp.open("GET",theUrl,true);
xhttp.send();
}
function documentEvents() {
var submitButton = document.getElementById('submit')
submitButton.addEventListener('click',
function(event) {
var formId = document.getElementById('test');
var name = document.getElementById('name');
var email = document.getElementById('email');
var password = document.getElementById('password');
myAction(name,email,password);
});
}
views.py:
from django.http import HttpResponse
from django.http import HttpResponseRedirect, HttpResponse
from .models import UserProfile
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def index(request):
req = request.method
t = request.GET
print(req)
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
savedata = UserProfile(name=name,email=email,password=password)
savedata.save()
print('Hello %s %s %s' % (name, email, password))
return HttpResponse('successfully inserted')
我的问题是如何从视图中发送数据以及如何在java脚本中获取数据。有没有办法在django视图中定义java脚本方法名称。请提供清晰的视图代码和java脚本