gpt4 book ai didi

javascript - 来自带有 Angular 和 django/python 的 URL 的 JSON

转载 作者:行者123 更新时间:2023-11-30 00:14:50 24 4
gpt4 key购买 nike

我有一个文件输入,当我选择一个 xlsx 文件时,它将被转换为 json 这已经可以工作了,唯一的问题是我想在我的 Angular 中使用 JSON。

我明白了:

应用程序.js

.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;

element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])

.service('fileUpload', ['$http', function ($http, $scope, response) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){

angular.json = $scope.json = response.converterfile;
})

.error(function(){
console.log("fail")
});
}
}])

.controller('ConverterCtrl', ['$scope', 'fileUpload', function($scope, fileUpload, response){

$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = 'converterfile/';
fileUpload.uploadFileToUrl(file, uploadUrl);

};

}])

我使用偏音,但这无关紧要。

转换器.html

<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
<input type="file" file-model="myFile"/>
<a class="btn btn-default" href="" ng-click="uploadFile()">upload me</a>


<div ng-controller="ConverterCtrl">
<table>
<tr ng-repeat="json in csv">
<td>{[ json.x ]} </td>

</tr>
</table>
</div>

后端是python

View .py

def converterfile(request):
''' Als de request methode POST is loop door onderstaande code heen'''
if request.method == 'POST':
filehandle = request.FILES['file']
sheet = filehandle.get_sheet()
out = json.dumps( [ row for row in sheet.array ] )
return HttpResponse(out)
else:
return HttpResponse("error")

所以我想从 url 中获取 jsonangular.json = $scope.json = response.converterfile;

但是它说

TypeError: Cannot read property 'converterfile' of undefined
at app.js:76
at angular.js:10296
at angular.js:14792
at r.$eval (angular.js:16052)
at r.$digest (angular.js:15870)
at r.$apply (angular.js:16160)
at g (angular.js:10589)
at T (angular.js:10787)
at XMLHttpRequest.w.onload (angular.js:10728)

有没有办法从 fileuploadurl 获取 json 并让它工作

最佳答案

首先不要将前端 错误与后端 代码混淆。如果您的前端发生问题,则问题出在前端代码中。

错误:无法读取未定义的属性“converterfile”。

这似乎是一个undefined 错误。这基本上意味着 undefined variable 。在这种情况下,会在 undefined object 上调用属性。

(仅供引用,属性是类似于 name.property 的属性)。

因此我们需要搜索converterfile 属性。因为这是引发错误的属性。

.success(function(){
angular.json = $scope.json = response.converterfile;
})

就是这样,问题是响应未定义。所以为了防止这个错误,我们需要在响应函数中添加response变量:

.success(function(response){
angular.json = $scope.json = response.converterfile;
})

关于javascript - 来自带有 Angular 和 django/python 的 URL 的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35132194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com